1👍
✅
I don’t see that you have even passed your form to your template from your view. When you call render it should look like this:
render(request,"login.html", {'login_form': login_form})
Now if you are using login_form
correctly in the template like so:
<div class='form-group'>
{{login_form.username}}
{{login_form.password}}
</div>
That will handle your errors for you and display them. If you want more fine grained control you could do this:
{% for field in login_form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
Now you can modify around each individual element. Please read this for more information on form rendering and this example: https://docs.djangoproject.com/en/1.10/topics/forms/#form-rendering-options
EDIT:
<form action="/login/" method="post" autocomplete="off">
{% csrf_token %}
<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">
{{login_form.username}}
</div>
<div class="form-group marb8 {% if login_form.errors.password %}errorput{% endif %}">
{{login_form.password}}
</div>
<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.erroes.items %}{{error}}{% endfor %}{{ msg }}</div>
<div class="auto-box marb38">
<a class="fr" href="forgetpwd.html">forget the password?</a>
</div>
<input class="btn btn-green" id="jsLoginBtn" type="submit" value="sign_in > " />
{% csrf_token %}
</form>
0👍
You have to pass just login_form as shown below if form is not valid. Because you are accessing login_form.errors.username in your template.
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
....
else:
return render(request,"login.html",{"login_form":login_form})
Source:stackexchange.com