Django:尝试制作自定义表单时出现 RelatedObjectDoesNotExist 错误

Django: RelatedObjectDoesNotExist error when trying to make custom form

嘿,我正在尝试制作自定义注册表单。问题是,我尝试注册某人,但出现相关对象不存在的错误,我不知道为什么。这是我的 views.py:

form = RegistrationForm()
if request.method=="POST":
    if request.POST['action']=="register":
        form = RegistrationForm(request.POST or None)
        if form.is_valid():
            form.save()

这是 forms.py 中的 RegistrationForm():

class RegistrationForm(UserCreationForm):

    fname = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'First Name','required':True}))
    lname = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Last Name','required':True}))
    email = forms.EmailField(max_length=256, label="Email", required=True, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email','required':True, 'type':'email'}))
    emailConfirm = forms.EmailField(max_length=256, label="", required=True, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Confirm Email','required':True, 'type':'email'}))
    password1 = forms.CharField(max_length=256, label="", required=True, widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder': 'Password','required':True}))
    password2 =forms.CharField(required=False)

    biography = forms.CharField(label = "Biography",required=False)
    research_place = forms.CharField(label="Research Place",required=False)
    studies = forms.CharField(label="Studies",required=False)

    class Meta:
        model = RegisterUser
        fields = ('email','emailConfirm','password1','biography','research_place','studies')
    def save(self,commit=True):
        RegisterUser = super(RegistrationForm,self).save(commit=False)
        RegisterUser.first_name=self.cleaned_data['fname']
        RegisterUser.last_name=self.cleaned_data['lname']
        RegisterUser.biography=self.cleaned_data['biography']
        RegisterUser.research_place="Def"
        RegisterUser.studies="Def"
        print (RegisterUser.studies)

        if commit:
            print("hurr")
            RegisterUser.save()
        return RegisterUser

还有我的models.py:

class RegisterUser(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    biography = models.CharField(max_length=1000000)
    research_place = models.CharField(max_length=1000000)
    studies = models.CharField(max_length=1000000)


    def set_password(self, raw_password):
        self.user.set_password(raw_password)
    USERNAME_FIELD='email'
    REQUIRED_FIELDS = ['fname', 'lname','password1']
    is_active=False

最后 admin.py:

class RegisterInline(admin.StackedInline):
    model = RegisterUser
    can_delete = False

class UserAdmin(BaseUserAdmin):
    inlines = (RegisterInline, )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

请让我知道我做错了什么,如果还有什么我应该改的。非常感谢!

完整跟踪: 回溯:

File "/Users/swedishfished/Desktop/tryDjango/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/swedishfished/Desktop/tryDjango/src/SignUp/views.py" in lOut
  122.                      form.save()
File "/Users/swedishfished/Desktop/tryDjango/src/SignUp/forms.py" in save
  48.       RegisterUser = super(RegistrationForm,self).save(commit=False)
File "/Users/swedishfished/Desktop/tryDjango/lib/python3.4/site-packages/django/contrib/auth/forms.py" in save
  93.         user.set_password(self.cleaned_data["password1"])
File "/Users/swedishfished/Desktop/tryDjango/src/SignUp/models.py" in set_password
  38.       self.user.set_password(raw_password)
File "/Users/swedishfished/Desktop/tryDjango/lib/python3.4/site-packages/django/db/models/fields/related.py" in __get__
  608.                 "%s has no %s." % (self.field.model.__name__, self.field.name)

终端错误:"POST /out HTTP/1.1" 500 82901

异常位置:/Users/swedishfished/Desktop/tryDjango/lib/python3.4/site-packages/django/db/models/fields/related.py in get, line 608

Django 会自动添加 UserCreationForm 中的所有用户字段。所以你只需要添加你的自定义内容。最重要的问题出在您的 Meta.model 和您的保存方法中。

替换注册表:

class RegistrationForm(UserCreationForm):
    biography = forms.CharField(label = "Biography",required=False)
    research_place = forms.CharField(label="Research Place",required=False)
    studies = forms.CharField(label="Studies",required=False)

    class Meta:
        # This tells Django to perform all the user actions and the standard
        # user model.  It does not care about RegisterUser.
        model = User
        fields =('email','emailConfirm','password1','biography','research_place','studies')

    def save(self,commit=True):
        # you were redefining RegisterUser before
        # First we need to save the user model,  we use a variable to work  
        # with the user instance.
        user = super(RegistrationForm,self).save(commit=False)
        user.username = user.email
        user.save()

        # Now we can save your custom RegisterUser
        r_user = RegisterUser(user=user,
                      biography=self.cleaned_data['biography'], 
                      research_place=self.cleaned_data['research_place'], 
                      studies=self.cleaned_data['studies'])
        if commit:
            r_user.save()
            print ('saving user: %s' % self.user)

        # We return the new RegisterUser instance which contains the user
        return r_user

清理模型:

class RegisterUser(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    biography = models.CharField(max_length=1000000)
    research_place = models.CharField(max_length=1000000)
    studies = models.CharField(max_length=1000000)

    # None of the stuff you had below is required