Alex Haines
Alex Haines

Reputation: 119

Django - User creates User and Profile in same form

Hi have changed my view from this: How to make User able to create own account with OneToOne link to Profile - Django

For some reason the profile_form is not saving the 'user' information to the database. I have checked the information in the print(profile_form.user) data and does show the username in the terminal. It is not however saving this foreign key to the database, it just leaves it Null.

To this: Views.py

class IndexView(View):
    template_name = 'homepage.html'
    form = UserCreationForm
    profile_form = ProfileForm

    def post(self, request):
        user_form = self.form(request.POST)
        profile_form = self.profile_form(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            profile_form.save(commit=False)
            profile_form.user = user
            print(profile_form.user)
            print(profile_form)
            profile_form.save()

            return render(request, self.template_name)
        else:
            return render(request, self.template_name, {'user_form': self.form,
                                                        'profile_form': self.profile_form})

    def get(self, request):
        if self.request.user.is_authenticated():
            return render(request, self.template_name)
        else:
            return render(request, self.template_name, {'user_form': self.form, 'profile_form': self.profile_form})

Forms.py

class ProfileForm(ModelForm):
    """
    A form used to create the profile details of a user.
    """
    class Meta:
        model = Profile
        fields = ['organisation', 'occupation', 'location', 'bio']

Models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    organisation = models.CharField(max_length=100, blank=True)
    occupation = models.CharField(max_length=100, blank=True)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)

Upvotes: 0

Views: 935

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

The user is an attribute of the instance, not the form.

    user = user_form.save()
    profile = profile_form.save(commit=False)
    profile.user = user
    print(profile.user)
    profile.save()

Upvotes: 2

Related Questions