Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can't get data from Django to html

views.py:

def index(request):
    if request.method == 'POST':
        data = request.POST['data']
        context = {'mydata': data}
        return render(request, 'home/index.html', context)
    else:
        html_template = loader.get_template('home/index.html')
        HttpResponse(html_template.render(request))

index.html:

<form method = 'POST' id = 'post-form'>
      <select name = 'data' id = 'data'> 
        <option> 1 </option>
        <option> 2 </option>
      </select>
      <button type="submit" name = 'post-form'> submit </button>
</form>

<h2> {{ mydata}} </h2> // this line print nothing.

When I click the submit button, I can access data from html submit in views.py.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, I can’t access mydata from Django in html.

How can I solve it?

>Solution :

There are minor mistakes in the code:

  1. You need to return HttpResponse so return HttpResponse(html_template.render(request)), but I’d recommend you to directly use return render(request, 'home/index.html').

  2. Also need to place {% csrf_token %} while dealing with POST data inside form, unless you have mentioned @csrf_exempt decorator on view.

So, try this code:

views.py:


def index(request):
    if request.method == 'POST':
        data = request.POST.get('data')
        context = {'mydata': data}
        return render(request, 'home/index.html', context)
    else:
        return render(request, 'home/index.html')
                    # OR  #
        # html_template = loader.get_template('home/index.html')
        # return HttpResponse(html_template.render({}, request))

index.html:

<form method='POST' id='post-form'>
    {% csrf_token %}
    <select name='data' id='data'> 
        <option> 1 </option>
        <option> 2 </option>
    </select>
    <button type="submit" name='post-form'> submit </button>
</form>
    
<h2> {{mydata}} </h2>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading