如何从视图django填充字段?唯一约束失败:auth_user.username

发布于 2025-01-30 20:54:04 字数 3006 浏览 2 评论 0原文

我正在尝试在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦亦如幻 2025-02-06 20:54:04

在评论中,您说您使用Django提供的通用用户。那么您的错误是您没有在表单中指定用户名字段。如果您尚未指定其他username_field,但在用户模型中,则需要此字段。而且您还没有,因为您只是导入它。在这种情况下,每个用户adminegrastrationform创建的没有用户名或实际具有 - 。因此,只要可以创建第一个用户,其次就会具有相同的(none用户名,并且它不会是唯一的。

要解决该问题,只需添加用户名字段。示例:

class AdminRegistrationForm(UserCreationForm):
    username = forms.CharField('username', max_length=150)
    ...

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 specify username field in your Form. This field is needed if you haven't specified other USERNAME_FIELD but in User model. And you haven't, because you just import it. In that case every User created with AdminRegistrationForm has no username, or actually has - None. So as long as first User might be created, second would have same (None) username and it wouldn't be unique.

To fix that issue just add username field. Example:

class AdminRegistrationForm(UserCreationForm):
    username = forms.CharField('username', max_length=150)
    ...

PS. USERNAME_FIELD = "eid" does nothing, because Resource is not an User model. Just create your own CustomUser model which is highly recommended by Django itself :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文