0

I am trying to implement an signup and login function.

This is my views.py:

here in auth.authenticate

def login(request):

    if request.method  == 'POST':
        f = auth.authenticate(email = request.POST['email'], password = request.POST['password'])
        print(f)
        if f is not None:
            auth.login(request,f)
            return redirect('home')
        else:
            return render(request,'login.html',{'error':'Wrong Username or password'})
    else:
        return render(request, 'login.html')

It always returns None and if I change to user and trying to login with username and password then it works fine it didn't work for email and password. i.e

 f = auth.authenticate(username= request.POST['username'], password = request.POST['password'])

I have tried request.get.POST('email') but not working, and I have also checked request.POST['email'] and request.POST['password'] contains valid info.

Himanshu Rahi
  • 255
  • 4
  • 15

1 Answers1

1

Django uses username field by default for authentication. If you want to use another field for authentication, you should extend the AbstractBaseUser and set email as the authentication field.

for settings.py:

AUTH_USER_MODEL = 'appname.User'

in your models.py:

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager

class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            email=self.normalize_email(email),
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email,
            password=password,
        )
        user.admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    email = models.EmailField(max_length=100, unique=True)
    #other fields..

    objects = MyUserManager()

    USERNAME_FIELD = 'email'

Also you can see another approach in Django - Login with Email

erdimeola
  • 844
  • 8
  • 17
  • 1
    AUTH_PROFILE_MODULE hasn't done anything for years. – Daniel Roseman Jul 15 '19 at 18:27
  • Thankyou very much it works but it kinda difficult but i found another way to do it..here what is have Done ````def login(request): if request.method == 'POST': username = get_object_or_404(User, email = request.POST['email']) f = auth.authenticate(username = username.username, password = request.POST['password']) if f is not None: auth.login(request,f) return redirect('home') else: return render(request,'login.html',{'error':'Wrong Username or password'}) else: return render(request, 'login.html')```` – Himanshu Rahi Jul 16 '19 at 15:31