0

所以,这就是我试图创建这两个模型的方式:

class UserManager(BaseUserManager):
    def create_user(self, email, username, year, branch, rollNo, password=None):
        if not email:
            raise ValueError("Users must have an email")
        if not username:
            raise ValueError("Users must have a username")
        if not year:
            raise ValueError("Users must specify an year")
        if not branch:
            raise ValueError("Users must specify a branch")
        if not rollNo:
            raise ValueError("Users must have a roll number")

        user = self.model(
                email=self.normalize_email(email),
                username=username,
                year=year,
                branch=branch,
                rollNo=rollNo
            )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_guest(self, username, college, year, email, password=None):
        if not username:
            raise ValueError("Please give a valid username")
        if not college:
            raise ValueError("Please provide your college")
        if not year:
            raise ValueError("Specify your year")
        if not email:
            raise  ValueError("A valid email needs to be provided")

        user = self.model(
                email = self.normalize_email(email),
                username = username,
                year = year,
                college = college
            )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, year, branch, rollNo, password):
        user = self.model(
                email=self.normalize_email(email),
                username=username,
                year=year,
                branch=branch,
                rollNo=rollNo,
                password=password
            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.set_password(password)
        user.save(using=self._db)
        return user

class GuestUser(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=30, unique=True)
    date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    year = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(1)], blank=False)
    college = models.CharField(max_length=50)
    guest = models.BooleanField(default=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'username', 'year', 'college']

    objects = UserManager()

    def __str__(self):
        return self.email + " - " + self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True



class User(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=30, unique=True)
    date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    year = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(1)], blank=False)
    Branch_CHOICES = (
        ('1', 'CSE'),
        ('2', 'ECE'),
        ('3', 'IT')
    )
    branch = models.CharField(max_length=3, choices=Branch_CHOICES)
    rollNo = models.CharField(validators=[MinLengthValidator(5)], max_length=5, unique=True)

    USERNAME_FIELD = 'rollNo'
    REQUIRED_FIELDS = ['email', 'username', 'year', 'branch']

    objects = UserManager()

    def __str__(self):
        return self.rollNo + " - " + self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

这是我的身份验证后端文件:

from django.contrib.auth.backends import BaseBackend
from events.models import User, GuestUser

class authBackend(BaseBackend):
    def authenticate(self, request, username, password):
        try:
            user = User.objects.get(rollNo=username)
            success = user.check_password(password)
            if success:
                return user
        except User.DoesNotExist:
            pass
        try:
            user = GuestUser.objects.get(username=username)
            success = user.check_password(password)
            if success:
                return user
        except GuestUser.DoesNotExist:
            pass
        return None

    def get_user(self, uid):
        try:
            return User.objects.get(pk=uid)
        except:
            return None

“用户”模型工作得很好,但我的“GuestUser”登录视图不能正常工作,这是我的观点:

def guest_login(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]

        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("events:index"))
        else:
            return render(request, "events/guest_login.html", {
                "message": "Invalid roll number and/or password."
            })
    else:
        return render(request, "events/guest_login.html")

我认为问题出在我的“身份验证”函数中,我要做的是获取“用户”对象并登录,如果用户对象为无,则获取“GuestUser”对象。但这显然不起作用,因为当我提交表单时,我被重定向到“success_url”但用户没有登录。有人可以帮我吗?

4

0 回答 0