[Django]-Django: RelatedObjectDoesNotExist error when trying to make custom form

2👍

Django will automatically add all the User fields from UserCreationForm. So you just need to add your custom stuff. The most significant issue was in your Meta.model and your save method.

Replace 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

Clean up model:

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

Leave a comment