如何从视图django填充字段?唯一约束失败:auth_user.username
我正在尝试在Django中的模板表单上填充字段。我试图在视图上做到这一点,并在表单模板上进行价值,但没有运气。这是我的工作,
结果是从资源模型中填充用户名和电子邮件字段,但是我得到唯一的约束失败:auth_user.username 错误。
谢谢
forms.py
class AdminRegistrationForm(UserCreationForm):
is_superuser = forms.BooleanField(),
password1 = forms.CharField(
label="Password",
widget=forms.PasswordInput)
password2 = forms.CharField(
label="Password Confirmation",
widget=forms.PasswordInput)
class Meta:
model = User
fields = ['password1', 'password2']
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if not password1 or not password2:
raise ValidationError("Please confirm your password")
if password1 != password2:
raise ValidationError("Passwords must match")
return password2
view.py
def admin_registration(request, username):
resources = Resource.objects.get(username=username)
if request.user.is_authenticated:
return redirect(reverse('index'))
if request.method == "POST":
resources = Resource.objects.get(username=username)
admin_registration_form = AdminRegistrationForm(request.POST)
if admin_registration_form.is_valid():
obj = admin_registration_form.save(commit=False)
obj.is_superuser = True
obj.save()
user = auth.authenticate(username=[resources.username],
password=request.POST['password1'])
if user:
auth.login(user=user, request=request)
messages.success(request, "You have successfully registered")
return redirect(reverse('index'))
else:
messages.error(request, "Unable to register your account at this time")
else:
admin_registration_form = AdminRegistrationForm()
return render(request, 'registration/registration.html', {
"registration_form": admin_registration_form, 'email': resources.email })
models.py
class Resource(models.Model):
ROLE = [
('Analyst', "Analyst"),
('Team Manager', "Team Manager"),
('Quality Auditor', "Quality Auditor"),
('Senior Analyst', "Senior Analyst"),
('', "")
]
username = models.CharField(max_length=254, default='')
status = models.IntegerField(default=1)
email = models.EmailField(max_length=254, null=False, default='')
email_sent = models.IntegerField(default=0)
name = models.CharField(max_length=254, default='')
surname = models.CharField(max_length=254, default='')
role = models.CharField(max_length=30, choices=ROLE, default='')
start_date = models.DateField()
end_date = models.DateField(null=True)
USERNAME_FIELD = "eid"
def __str__(self):
return self.email
I am trying to populate a field on a template form in Django. I have tried to do it on the view as well as a value on the form template but no luck. Here is my work
The outcome would be to populate username and email field from the resource model, but I am getting an UNIQUE constraint failed: auth_user.username error.
Thanks
forms.py
class AdminRegistrationForm(UserCreationForm):
is_superuser = forms.BooleanField(),
password1 = forms.CharField(
label="Password",
widget=forms.PasswordInput)
password2 = forms.CharField(
label="Password Confirmation",
widget=forms.PasswordInput)
class Meta:
model = User
fields = ['password1', 'password2']
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if not password1 or not password2:
raise ValidationError("Please confirm your password")
if password1 != password2:
raise ValidationError("Passwords must match")
return password2
view.py
def admin_registration(request, username):
resources = Resource.objects.get(username=username)
if request.user.is_authenticated:
return redirect(reverse('index'))
if request.method == "POST":
resources = Resource.objects.get(username=username)
admin_registration_form = AdminRegistrationForm(request.POST)
if admin_registration_form.is_valid():
obj = admin_registration_form.save(commit=False)
obj.is_superuser = True
obj.save()
user = auth.authenticate(username=[resources.username],
password=request.POST['password1'])
if user:
auth.login(user=user, request=request)
messages.success(request, "You have successfully registered")
return redirect(reverse('index'))
else:
messages.error(request, "Unable to register your account at this time")
else:
admin_registration_form = AdminRegistrationForm()
return render(request, 'registration/registration.html', {
"registration_form": admin_registration_form, 'email': resources.email })
models.py
class Resource(models.Model):
ROLE = [
('Analyst', "Analyst"),
('Team Manager', "Team Manager"),
('Quality Auditor', "Quality Auditor"),
('Senior Analyst', "Senior Analyst"),
('', "")
]
username = models.CharField(max_length=254, default='')
status = models.IntegerField(default=1)
email = models.EmailField(max_length=254, null=False, default='')
email_sent = models.IntegerField(default=0)
name = models.CharField(max_length=254, default='')
surname = models.CharField(max_length=254, default='')
role = models.CharField(max_length=30, choices=ROLE, default='')
start_date = models.DateField()
end_date = models.DateField(null=True)
USERNAME_FIELD = "eid"
def __str__(self):
return self.email
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在评论中,您说您使用Django提供的通用
用户
。那么您的错误是您没有在表单中指定用户名
字段。如果您尚未指定其他username_field
,但在用户
模型中,则需要此字段。而且您还没有,因为您只是导入它。在这种情况下,每个用户
用adminegrastrationform
创建的没有用户名
或实际具有 -无
。因此,只要可以创建第一个用户
,其次就会具有相同的(none
)用户名
,并且它不会是唯一的。要解决该问题,只需添加
用户名
字段。示例:PS。
username_field =“ eid”
什么都不做,因为资源
不是用户
模型。只需创建自己的customuser
高度由django推荐本身:)In comment you said that you use generic
User
that Django is providing. Then your mistake is that you didn't specifyusername
field in your Form. This field is needed if you haven't specified otherUSERNAME_FIELD
but inUser
model. And you haven't, because you just import it. In that case everyUser
created withAdminRegistrationForm
has nousername
, or actually has -None
. So as long as firstUser
might be created, second would have same (None
)username
and it wouldn't be unique.To fix that issue just add
username
field. Example:PS.
USERNAME_FIELD = "eid"
does nothing, becauseResource
is not anUser
model. Just create your ownCustomUser
model which is highly recommended by Django itself :)