Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Customer with onetoone relationship with User – how to create the fields for that model when creating User?

Here is my problem – upon creation of User in django i want to also create Customer with Onetoone relationship. I was able to get this working but problem started when I wasn’t able to also create fields – dob and mobile. (User is default django user)

My forms.py

    class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
    mobile = CharField(max_length=30)
    
class CreateCustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['mobile', 'dob']

My models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Customer(Model):
    user = OneToOneField(User, on_delete=CASCADE)
    mobile = CharField(max_length=12,null=True)
    dob = DateField(null=True)

    def __str__(self):
        return self.user.username

My views.py

def customer_registration(request):
    form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            Customer.objects.create(
                user=user, 
            )
            messages.success(request, 'Account was created for ' + username)
            return redirect('index')
    context = {'form': form}
    return render(request, 'signup.html', context)

I need to add 2 more fields into that Customer model (dob=form.dob, mobile=form.mobile), I was trying to have second form for this but it wouldn’t work. This is what I have tried:

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save()

            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            if request.method == 'POST':
                form2 = CreateCustomerForm(request.POST)
                
                mobile = form2['mobile']

                Customer.objects.create(
                user=user, mobile=mobile)
                messages.success(request, 'Account was created for ' + username)
                return redirect('index')
            else:
                print('Error')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)

and:

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        form2 = CreateCustomerForm(request.POST)
        if form.is_valid() and form2.is_valid():
            user = form.save()
            mobile = form2.save()
            username = form.cleaned_data.get('username')
            group = Group.objects.get(name='customer')
            user.groups.add(group)
            Customer.objects.create(
                user=user, mobile=mobile,
            )
            messages.success(request, 'Account was created for ' + username)
            return redirect('index')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)

I really got stock on this one. Any ideas?

>Solution :

THe only problem is that your CreateCustomerForm does not assign a value to the user field of the Customer, you can set the .user of the .instance wrapped in the second form (form2):

def customer_registration(request):
    form = CreateUserForm()
    form2 = CreateCustomerForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        form2 = CreateCustomerForm(request.POST)
        if form.is_valid() and form2.is_valid():
            user = form.save()
            form2.instance.user = user  # 🖘 assign to the user of the customer
            form2.save()
            username = user.username
            messages.success(request, f'Account was created for {username}')
            return redirect('index')
    context = {'form': form, 'form2': form2}
    return render(request, 'signup.html', context)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading