retro_coder
retro_coder

Reputation: 456

How to add 2 models in a registration form in Django?

I want to create a Registration form which includes two models. One model is my custom model (Profile) and the other is the default User model in Django. I created two separate forms within the same template but the data is not successfully stored. This is what I had done so far:

models.py:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    company = models.CharField(max_length=100, blank=True, null=True)
    address = models.TextField()

views.py:

def register(request):
    if request.method == 'POST': 
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():  
            user_form.save()
            profile_form.save()
            return redirect('login')
    else:
        user_form = UserForm()
        profile_form = ProfileForm()
    return render(request, 'register_page.html', {'user_form': user_form, 'profile_form': profile_form})

forms.py:

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

class UserForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class ProfileForm(forms.ModelForm): 

    class Meta:
        model = Profile
        fields = ['company', 'address']

However, when I tried to register a new user, the data gets saved in the User model (username, email, password) but not in the Profile model (company, address).

I am getting this error instead:

RelatedObjectDoesNotExist at /
Profile has no user.

What should I do?

Upvotes: 2

Views: 1661

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

Since your Profile model is connected to the User model through OneToOne relation so you need to assign the user to your profile like this.:

if user_form.is_valid() and profile_form.is_valid():
user = user_form.save() profile = profile_form.save(commit = False)
# assign user to your profile
profile.user = user profile.save()
return redirect('login')

Upvotes: 4

Related Questions