Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AuthenticationForm in Django

I'm attempting to use the AuthenticationForm form with django and finding out that I can't seem to get the form to validate. I widdled it down to a simple test(assuming it's correct) that doesn't seem to work. Can anyone see a problem here?

>>> from django.contrib.auth.forms import AuthenticationForm >>> POST = { 'username': 'test', 'password': 'me', } >>> form = AuthenticationForm(POST) >>> form.is_valid() False 

Is there a real reason it won't validate? Am I using it incorrectly? I've basically modeled it after django's own login view.

like image 551
Mike Shultz Avatar asked Dec 07 '11 19:12

Mike Shultz


People also ask

How do I authenticate username and password in Django?

from django. contrib. auth import authenticate user = authenticate(username='john', password='secret') if user is not None: if user. is_active: print "You provided a correct username and password!" else: print "Your account has been disabled!" else: print "Your username and password were incorrect."

How do I login as user in Django?

Django by default will look within a templates folder called registration for auth templates. The login template is called login. html . Create a new directory called templates and within it another directory called registration .

How do I authenticate an email in Django?

Email authentication for Django 3.x For using email/username and password for authentication instead of the default username and password authentication, we need to override two methods of ModelBackend class: authenticate() and get_user():


2 Answers

Try:

form = AuthenticationForm(data=request.POST) 
like image 104
Brandon Avatar answered Sep 23 '22 02:09

Brandon


After a few hours spent finding "Why the hack there are no validation error?!" I run into this page: http://www.janosgyerik.com/django-authenticationform-gotchas/

AuthenticationForm 's first argument is not data! at all:

def __init__(self, request=None, *args, **kwargs): 

So thats why you have to pass req.POST to data or pass something else in the first argument. It was already stated in one of the answers here to use:

AuthenticationForm(data=req.POST) 

You can also use one of these:

AuthenticationForm(req,req.POST) AuthenticationForm(None,req.POST) 
like image 29
darkless Avatar answered Sep 25 '22 02:09

darkless