I have a custom Django login page. I want to throw an exception when username or password fields are empty. How can I do that?
My view.py log in method :
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
print("auth",str(authenticate(username=username, password=password)))
if user:
# Is the account active? It could have been disabled.
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse("xxx.")
else:
# Bad login details were provided. So we can't log the user in.
print ("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/profile.html', {}, context)
I tried this and it didn't work: This is forms.py
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise forms.ValidationError('username does not exist.')
The correct approach is to use forms, instead of fetching the variables directly from request.POST
. Django will then validate the form data, and display errors when the form is rendered in the template. If a form field is required, then Django will automatically display an error when the field is empty, you don't even need to write a clean_<field_name>
method for this.
Django already has a built in login view. The easiest approach is to use this rather than writing your own. If you still want to write your own view, you will still find it useful to look at how Django does it.
You can use login view, which is provided by Django. So your login.html should look like that example.
<form class="login" method="POST" action="/login/">
{% csrf_token %}
{{form.as_p}}
<li><input type="submit" class="logBut" value="Log in"/></li>
</form>
And remember urls.py !
url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With