无法让OneToOneField使用表单

时间:2018-10-09 21:24:36

标签: python django python-3.x django-2.1

我正在尝试向Django的默认用户模型添加更多字段。我正在使用OneToOneField方法。我想创建一个注册页面,该页面允许用户填写用户名,密码,电子邮件和其他要添加到单独的Profile模型中的字段。 我使用了一些发现的代码片段,并试图使其工作。但是,我不断收到IntegrityError at /account/signup/ UNIQUE constraint failed: accounts_profile.user_id错误。 我认为问题在于,当创建用户时,也会创建配置文件。然后,当使用用户的主键创建新的配置文件时,它会给出错误,因为该主键的配置文件已经存在。 有人可以告诉我正确的方法吗?

这里是所有相关代码:

models.py:

from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    GENDER_CHOICES = (
        ('MALE', 'Male'),
        ('FEMALE', 'Female')
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    middle_name = models.CharField(max_length=30, blank=True, default='')
    prefix = models.CharField(max_length=6, blank=True, default='')
    suffix = models.CharField(max_length=10, blank=True, default='')

    def __str__(self):
        return self.user.username


@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

forms.py

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

from .models import Profile


class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2',
        )

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user


class ProfileForm(ModelForm):

    class Meta:
        model = Profile
        fields = (
            'middle_name',
            'prefix',
            'suffix',
        )

    def save(self, commit=True):
        profile = super(ProfileForm, self).save(commit=False)
        profile.middle_name = self.cleaned_data['middle_name']
        profile.prefix = self.cleaned_data['prefix']
        profile.suffix = self.cleaned_data['suffix']

        if commit:
            profile.save()

        return profile

views.py

...
def signup_view(request):
    if request.method == 'POST':
        register = RegistrationForm(request.POST, prefix='register')
        userprofile = ProfileForm(request.POST, prefix='profile')
        print(register.is_valid())
        print(userprofile.is_valid())
        if register.is_valid() * userprofile.is_valid():
            user = register.save()
            profile = userprofile.save(commit=False)
            print(user)
            profile.user = user
            profile.save()

            return HttpResponse('congrats')
        else:
            return HttpResponse('errors')
    else:
        userform = RegistrationForm(prefix='register')
        userprofileform = ProfileForm(prefix='profile')
        return render(request, 'accounts/signup.html', {'userform': userform,
                                                        'userprofileform': userprofileform})

0 个答案:

没有答案