Getting None instead of Value from HTML form (Django)

Question:

Here below my HTML-template

<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
   {% csrf_token %}
   <h2>
      {{ result }}
   </h2>
   <div class="d-flex justify-content-center">
      <button type="submit" class="btn btn-primary">Show</button>
   </div>
</form>

my View.py

def show_result(request):
    if request.method == "POST":
        result = request.POST.get('test')
        return HttpResponse(result)

By pressing the button ‘Show’ I got None instead of {{ result }} value.
So, how I can get a Value inside curly brackets?
Thanks a lot for any help.

Asked By: Ches_Ter

||

Answers:

In order to submit the data, they need to be values of form elements like input, textarea, select options…
You can choose the right type for the input field. You can make use of the hidden field type to submit data that will not be displayed to the client…
You probably do not need to use the heading inside the form.

<h2>{{ result }}</h2>
<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
{% csrf_token %}
<div class="d-flex justify-content-center">
   <input type="hidden" name="result_field" value="{{ result }}" />
   <button type="submit" class="btn btn-primary">Show</button>
</div>
</form>

On the backend, you can retrieve the data as follow:

result = request.POST.get('result_field')

I hope that works for you.

Answered By: Kossi D. T. S.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.