Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging "add" form in Django Admin from 2 or more Models (connected with one-to-one relationship)

Tags:

python

django

I have a Django's default UserCreationForm to add a new user via Admin app. I want to add new fields from another custom model called UserProfile. The UserProfile has a One-to-One relationship with Django's User model. The additional fields which UserProfile model has are phone number, company name etc.

Is there a way where I can merge UserProfile form with Django's default User form while creation of the new user from Admin panel?

I looked at Django's documentation here on Inline forms but seems their require foreign key relationship.

Django 2.1

like image 648
disp_name Avatar asked Apr 10 '19 13:04

disp_name


People also ask

How can I have multiple models in a single Django ModelForm?

In a nutshell: Make a form for each model, submit them both to template in a single <form> , using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model.

What is forms ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


1 Answers

Assuming you have Profile with extra field phone_number. Like this

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    phone_number = models.CharField(max_length=24)

You can follow following steps to add extra fields in UserCreationForm in Admin.

1. Create custom UserCreationForm

Inherit from UserCreationForm and Add extra fields and functionality.

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

class UserWithProfileCreationForm(UserCreationForm):
    phone_number = forms.CharField(max_length=32)

    def save(self, commit=True):
        instance = super().save(commit=True)
        profile = Profile(user=instance, phone_number=self.cleaned_data['phone_number'])
        profile.save()
        return instance

2. Unregister (already registered) User model and register again with custom form and fields

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

# unregister first
admin.site.unregister(User)


@admin.register(User)
class UserWithProfileAdmin(UserAdmin):
    add_form = UserWithProfileCreationForm
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            # add any custom fields here
            'fields': ('username', 'password1', 'password2', 'phone_number'),
        }),
    )
like image 94
Nafees Anwar Avatar answered Oct 09 '22 09:10

Nafees Anwar