user10784511
user10784511

Reputation:

Authenticating the username and password returns user as none during logn

While i am authenticating the login form using authenticate function i am getting user as none eventhough getting the username and password.

settings.py:
---------
AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend",)
forms.py:
----------
class UserRegistrationForm(forms.Form):
    fname = forms.CharField(required=True,label='FirstName',max_length=32)

    lname = forms.CharField(required=True,label='LastName',max_length=32)

    username = forms.CharField(required = True,label = 'Username',max_length = 32)

    password = forms.CharField(required = True,label = 'Password',max_length = 32,min_length=8)

class login_form(forms.Form):
    username = forms.CharField()
    password1 = forms.CharField(widget=forms.PasswordInput)

views.py:
--------
def signup(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            userObj = form.cleaned_data
            username = userObj['username']
            password = userObj['password']
            fname = userObj['fname']
            lname = userObj['lname']
            print (username,password,fname,lname)
            if(len(password)<8):
                messages.error(request,"This password length should be minimum 8 characters")
                # raise ValidationError("This password length should be minimum 8 characters ")
            if not (User.objects.filter(username=username).exists()):
                p = Event(fname=fname, lname=lname, username=username, password=password)
                p.save()
                # return HttpResponseRedirect('Login.html')
                return redirect('/Login/')
            else:
                raise forms.ValidationError('Looks like a username with that username or password already exists')
    else:
        form = UserRegistrationForm()
    return render(request, 'signup.html', {'form':form})
def Login(request):
    form = login_form(request.POST or None)
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password1")
            print (username,password)
            user = authenticate(username=username, password=password)
            print('user is', user)
models.py
:--------
class MyUserManager(BaseUserManager):
 def create_user(self, fname,lname,username, password):
      """
      Creates and saves a User with the given username, date of
      birth and password.
      """
      if not username:
           raise ValueError('Users must have an username')
      user = self.model(username=username,fname=fname,lname=lname)
      user.set_password(password)
      user.save(using=self._db)
      return user


 def create_superuser(self, fname,lname,username, password,email=None):
      """
      Creates and saves a superuser with the given username and password.
      """
      user = self.create_user(
           fname=fname,
           lname=lname,
           username=username,
           password=password,
      )
      user.is_admin = True
      user.is_superuser = True
      user.save(using=self._db)
      return user

class Event(AbstractBaseUser):
     fname = models.CharField('fname', max_length=120)
     lname = models.CharField('lname',max_length=120)
     username = models.CharField('username',max_length = 60,unique=True)
     password = models.CharField('password',max_length=120,default='pavi@2789')

     USERNAME_FIELD = 'username'
     REQUIRED_FIELDS = ['fname','lname']

     objects = MyUserManager()

     def __unicode__(self):
          return self.username

     class Meta:
          # managed = False
          db_table = "user"
          # fields = ('username', 'fname', 'lname',  'password', 'password2')

In database side the login credentials are saved.I dont know what is going wrong here.

Here Event is nothing but the model which i have created .

I have updated my models.py with the AbstractBaseUser, BaseUserManager and login using the superuser credentials it is working but when i am creating the user with the singup form the login is not working and throwing me the error as Manager isn't available; 'auth.User' has been swapped for 'Provisioning.Event'

Upvotes: 0

Views: 542

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599460

This isn't right at all. You can't just declare a random model and expect it to work for authentication. You need to subclass AbstractBaseUser and add your fields, declare your model in the AUTH_USER_MODEL setting, and set the password appropriately on save.

from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager

class Event(AbstractBaseUser):
     ...

And in settings.py:

AUTH_USER_MODEL = 'myapp.Event'

Now, when you create the user in the view, you need to use set_password to hash the password:

p = Event(fname=fname, lname=lname, username=username)
p.set_password(password)
p.save()

Also, note that the checking of existing usernames should be taken care of in the view - which would happen automatically if you used a ModelForm. Even better, use the built-in UserCreationForm from django.contrib.auth.forms. (But whatever you do, note that it makes no sense at all to filter on User, since you aren't using that model at all.)

Upvotes: 1

Nikolas Stevenson-Molnar
Nikolas Stevenson-Molnar

Reputation: 4680

The problem is not with the call to authenticate, but probably with how you are implementing the custom user model.

Using a custom user model is totally fine, and is very useful, but if you want to keep things easy for yourself, let Django handle the password part.

There's a great guide on how to write your own user model and still have it play nicely with built-in Django functionality, like authentication: https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#specifying-a-custom-user-model

The reason for this is because Django hashes passwords for storage in the database for security. There's a lot of nuance to how Django handles passwords. It's quite fascinating if you're interested: https://docs.djangoproject.com/en/2.1/topics/auth/passwords/#how-django-stores-passwords

Upvotes: 0

Related Questions