Custom Django Login Page

I have a custom Django login page. I want to throw an exception when the username or password fields are empty. How can i do this?

My log.py login 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 did not work: This is form.py

 def clean_username(self): username = self.cleaned_data.get('username') if not username: raise forms.ValidationError('username does not exist.') 
+7
python django validation login
source share
2 answers

You can use the login view provided by Django. So your login.html should look like this.

 <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'}), 
+6
source share

The correct approach is to use forms instead of extracting variables directly from request.POST . Django then validates the form data and displays errors when the form is displayed 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, it will still be useful for you to see how Django does it.

+4
source share

All Articles