How to preserve form fields in django after unsuccessful submit?
In your template you are not making use of form
passed by the view.
You can update part of your template as (assuming your field names in the form are first_field
and second_field
.
<form action="/feedback/" method="POST">
{% csrf_token %}
<div class="article">
<label for="name">
Ваше имя:
</label>
<br />
{{ form.first_field.errors }}
{{ form.first_field.label_tag }}: {{ form.first_field }}
<br />
<!-- class="inputbox required" -->
{{ form.second_field.errors }}
{{ form.second_field.label_tag }}: {{ form.second_field }}
<br />
<input type="submit" name="submit" value="Отправить">
</div> <!-- /article -->
</form>
For more reference - Displaying form using template
You need to pass the form back to the template; and you need to render the form in the template as per jpic's link.
The following should render your form errors:
from django.shortcuts import render, redirect
def feedback(request):
ctx = {}
ctx['articles'] = Comment.objects.all()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
form.save()
return redirect('/thanks')
else:
ctx['form'] = form
return render(request, 'feedback.html', ctx)
else:
ctx['form'] = CommentForm()
return render(request, "feedback.html", ctx)
In your template:
{% extends "base.html" %}
{% block main %}
<table>
<form action="/feedback/" method="POST">
{% csrf_token %}
<div class="article">
{{ form }}
<br />
<input type="submit" name="submit" value="Отправить">
</div> <!-- /article -->
</form>
</table>
{% include "articles.html" %}
{% endblock %}