Home > Software design >  can't get data from Django to html
can't get data from Django to html

Time:08-02

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.

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

How can I solve it?

CodePudding user response:

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>
  • Related