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
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.
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.
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'),
}),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With