Django用户邮箱验证报错:'User'对象无'user'属性
问题解决:Django激活邮箱时出现
AttributeError: 'User' object has no attribute 'user' 问题背景
开发了一个包含身份认证与邮箱验证功能的Django Web应用,支持Customer和Employee两种用户身份,通过继承AbstractUser的User模型关联这两个子模型。在邮箱激活的activate函数中,尝试用user.user.signup_confirmation = True设置字段时触发上述错误。
错误原因
查看models.py的定义可知,signup_confirmation字段是直接定义在自定义User模型中的属性,并非嵌套在user子属性下。你错误地多写了一层.user,导致程序找不到对应属性。
修复方案
修改activate函数中的代码,将user.user.signup_confirmation = True改为直接操作User对象的signup_confirmation字段:
def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True # 修正此处,直接操作user对象的signup_confirmation字段 user.signup_confirmation = True user.save() login(request, user) return redirect('index') else: return render(request, 'activation_invalid.html')
额外优化建议
- 用户身份标记:在用户注册为Customer或Employee时,需同步设置
User模型中的is_customer或is_employee字段为True,示例如下(以CustomerSignUpForm为例):
class CustomerSignUpForm(UserCreationForm): # 表单字段定义 class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def save(self, commit=True): user = super().save(commit=False) user.is_customer = True if commit: user.save() Customer.objects.create(user=user, phone_number=self.cleaned_data['phone_number'], location=self.cleaned_data['location']) return user
- 邮件收件人优化:当前注册视图中邮件收件人写死为
['to@example.com'],建议改为使用用户注册时填写的邮箱:[user.email]。
内容的提问来源于stack exchange,提问作者P Studio
相关产品推荐
相关产品推荐

