Django: RelatedObjectDoesNotExist error when trying to make custom form

时间:2016-03-04 18:13:00

标签: python django forms registration

hey all i'm trying to make a custom registration form. The problem is, I try to register someone, and I get the error that related object does not exist, and i have no idea why. Here is in my 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()

Here is the RegistrationForm() in forms.py:

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

And my 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

And finally 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)

please let me know what I am doing wrong, and if there is anything else I should change. Thanks so much!

Full trace: Traceback:

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)

Errro in terminal: "POST /out HTTP/1.1" 500 82901

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

1 个答案:

答案 0 :(得分:1)

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

替换RegistrationForm:

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