【问题标题】:UNIQUE constraint failed username error while changing user details更改用户详细信息时唯一约束失败用户名错误
【发布时间】:2016-01-18 08:57:56
【问题描述】:

我通过扩展AbstractUser 类来自定义用户模型。我想制作表格来更改用户的全名和网站字段。 我的用户:

class Hacker(AbstractUser):
    name = models.CharField(max_length=255)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True, null=True)
    description = models.CharField(max_length=255, blank=True, null=True)
    website = models.URLField(max_length=200, blank=True, null=True)

    def __str__(self):
        if self.name:
            return self.name
        else:
            return self.username

和forms.py:

class ProfileForm(forms.ModelForm):
    """
    Edit profile form
    """
    name = forms.CharField(label=_("Name"),
                           widget=forms.TextInput(attrs={'placeholder': _('Name')}))
    description = forms.CharField(label=_("Description,Position"), required=False,
                                  widget=forms.TextInput(attrs={'placeholder': _('Description, Position')}))
    website = forms.URLField(label=_("Website"), required=False,
                             widget=forms.TextInput(attrs={'placeholder': _('Website URL')}))

    class Meta:
        model = get_user_model()
        fields = ['name', 'description', 'website']

在页面中我使用 {{ field }} 添加输入并在 POST 部分视图中:

form = ProfileForm(request.POST)
    if form.is_valid():
        form.save(commit=True)
        ...

但是form.save 给出了UNIQUE constraint failed: common_hacker.username 错误。这里有什么问题?

【问题讨论】:

  • Ref docs.djangoproject.com/en/1.9/topics/auth/customizing/… 您正在扩展 django 的标准用户模型 (docs.djangoproject.com/en/1.9/ref/contrib/auth/…),这意味着您的用户需要拥有唯一的用户名。您是否尝试使用/更改用户名字段?
  • @TomDalton 不,该表单不会修改用户名或密码字段。由于扩展AbstractUser 类,存在用户名字段。在admin和rest-api(django rest框架)中添加、修改用户没有问题。但我不知道为什么它会以这种形式出现这样的错误。我在想它会尝试创建新用户,但不确定。

标签: python django django-forms


【解决方案1】:

在创建表单时添加instance=request.user修复问题:

form = ProfileForm(request.POST, instance=request.user)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 2019-01-18
    • 2018-03-11
    • 1970-01-01
    • 2018-01-19
    • 2011-12-12
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多