Django 用户令牌没有得到创建它的用户的身份验证

Django user token is not getting authenticated by the user by which it is created

i 创建一个视图函数以在 link 的帮助下将 user.is_active 设置为 true 以在 django

中激活用户帐户

link包含uidb64和token

我在注册时生成令牌并通过电子邮件发送 link 未获得用户身份验证

这里是link发送函数

def register(request):
    error = None
    if request.method == 'POST':
        form = RegisterUser(data= request.POST)
        email = request.POST['email']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        phone_number = request.POST['phone_number']
        password = request.POST['password']
        password1 = request.POST['password1']
        username = request.POST['email']

        if (email) and (first_name) and (last_name) and (phone_number) and (password) and (password1) and (username):
            try:    
                user = Account.objects.get(username = username)
                error = 'user with this email already exists'
                return render(request, 'account/register.html', {'error':error})
            except Account.DoesNotExist:
                if password == password1:
                    user = Account.objects.create_user(email= email,first_name= first_name,last_name= last_name,password= password, username=username)
                    user.phone_number = phone_number    
                    # user activation
                    current_site = get_current_site(request)
                    email_subject = 'Activate your account'
                    message = render_to_string('account/email.html',{'user': user , 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)) , 
                    'token':default_token_generator.make_token(user)
                    })
                    email_from = settings.EMAIL_HOST_USER
                    to_email = email
                    send_email = EmailMessage(email_subject, message , to=[email])
                    send_email.send()
                    user.save()
                    print(user)
                else:
                    error = "Passwords didn't match"
                    return render(request, 'account/register.html', {'error':error})
        else:
            error = 'Fill the form correctly'
            return render(request, 'account/register.html', {'error':error})
    context = {
    }
    return render(request, 'account/register.html',context)

这是我检查令牌的代码

def activate(request, uidb64 ,token):

    try:
        uid = urlsafe_base64_decode(uidb64).decode()
        user = Account._default_manager.get(pk = uid)
    except (TypeError,ValueError,OverflowError,Account.DoesNotExist):
        user = None
    print(default_token_generator.check_token(user, token))
    # This is retruning false
    if user is not None:
        if default_token_generator.check_token(user, token):
            user.is_active = True
            user.email = 'gnai'
            user.save()
            print(user)
            print('thosi')
            print(user.email)
            return render(request , 'core/base.html')
        else:
            print(',a')

问题在于 打印(default_token_generator.check_token(用户,令牌)) 这是返回 False

这是我创建用户的方法

class MyAccountManager(BaseUserManager):
    def create_user(self,first_name, last_name, username, email , password =None):
        if not email:
            raise ValueError('Email Address is not present.')
        if not username:
            raise ValueError('Username is not present')

        user = self.model(
            email = self.normalize_email(email),
            username = username,
            first_name = first_name,
            last_name = last_name,
            )

        user.set_password(password)
        user.save(using= self._db)
        return user

    def create_superuser(self,first_name, last_name, username, email , password):
        user = self.create_user(
            email = self.normalize_email(email),
            username = username,
            first_name = first_name,
            last_name = last_name,
            password = password,
            )
        user.is_admin = True
        user.is_staff = True
        user.is_active = True
        user.is_superadmin = True
        user.save(using= self._db)
        return user


# Create your models here.
class  Account(AbstractBaseUser):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    username = models.CharField(max_length=50 , unique=True)
    email  = models.EmailField(max_length = 100 , unique=True)
    phone_number = models.CharField( max_length=50)

# required fields for 
    date_joined  = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_superadmin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name' ,'last_name']
    objects = MyAccountManager()

    def __str__(self):
        return self.email

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

    def has_module_perms(self , add_label):
        return True

如果需要任何额外信息,请在下方评论 谢谢!

我找到了答案 正如我们所知,令牌也使用时间来生成令牌 然后我的情况是它使用上次登录时间来生成令牌 然后 现在寻求解决方案 我在生成令牌令牌之前移动 user.save

现在新代码是这样的

def register(request):
    error = None
    if request.method == 'POST':
        form = RegisterUser(data= request.POST)
        email = request.POST['email']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        phone_number = request.POST['phone_number']
        password = request.POST['password']
        password1 = request.POST['password1']
        username = request.POST['email']

        if (email) and (first_name) and (last_name) and (phone_number) and (password) and (password1) and (username):
            try:    
                user = Account.objects.get(username = username)
                error = 'user with this email already exists'
                return render(request, 'account/register.html', {'error':error})
            except Account.DoesNotExist:
                if password == password1:
                    user = Account.objects.create_user(email= email,first_name= first_name,last_name= last_name,password= password, username=username)
                    user.phone_number = phone_number    
                    user.save()
                    token =default_token_generator.make_token(user)
                    print(user)
                    print(token)
                    # user activation
                    current_site = get_current_site(request)
                    email_subject = 'Activate your account'
                    message = render_to_string('account/email.html',{'user': user , 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)) , 
                    'token':token,
                    })
                    email_from = settings.EMAIL_HOST_USER
                    to_email = email
                    send_email = EmailMessage(email_subject, message , to=[email])
                    send_email.send()
                    print(user)
                    print(token)
                else:
                    error = "Passwords didn't match"
                    return render(request, 'account/register.html', {'error':error})
        else:
            error = 'Fill the form correctly'
            return render(request, 'account/register.html', {'error':error})
    context = {
    }
    return render(request, 'account/register.html',context)