我通过扩展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
错误。这可能有什么问题?
答案 0 :(得分:0)
在创建表单已修复问题时添加instance=request.user
:
form = ProfileForm(request.POST, instance=request.user)