Add adding icon to ModelChoiceField

hey, I have a custom User model with an organization FK field. I want to edit the add_form for the user creation to show this field and I want to make it required with the ability to add new organizations

users/admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import CustomUser, Organization

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'name', 'organization', 'user_type')
    
    name = forms.CharField(max_length=150)
    # organization = forms.ModelChoiceField(queryset=Organization.objects.all(), blank=True)
class CustomUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('Personal info', {'fields': ('name', 'organization', 'user_type')}),
        ('Permissions', {
            'fields': ('credential_sent', 'is_active', 'is_staff', 'is_superuser',),#  'groups', 'user_permissions'
        }),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'name', 'organization', 'user_type', 'password1', 'password2'),
        }),
    )
    list_display = ('username', 'name', 'organization', 'user_type', 'is_staff')
    readonly_fields = ('date_joined', 'last_login')
    search_fields = ('username', 'name', 'organization__name')
    ordering = ('username',)
    add_form = CustomUserCreationForm

class OrganizationAdmin(admin.ModelAdmin):
    list_display = ['name']
    search_fields = ['name']

admin.site.register(CustomUser, CustomUserAdmin)
admin.site.register(Organization, OrganizationAdmin)

when I run this code I get this page:


the field is not required but I do see the add option
when I uncomment this line:

    # organization = forms.ModelChoiceField(queryset=Organization.objects.all(), blank=True)

I get:

So now it is required but I can not add new organizations.
What am I not doing correctly and how to fix it?
I want the field to be required and in the form with the ability to add new organizations

Thank you!

Hi,

So you want to make the organization field required and also allow users to add new organizations during user creation. Correct?

If that is the case, you need to:

  1. Customize the CustomUserCreationForm to include a field for adding new organizations.
  2. Override the form’s save method to handle the creation of new organizations if provided.

Something like that:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import CustomUser, Organization

class CustomUserCreationForm(UserCreationForm):
    new_organization = forms.CharField(max_length=150, required=False, help_text="Add a new organization if it doesn't exist.")
    
    class Meta:
        model = CustomUser
        fields = ('username', 'name', 'organization', 'user_type')
    
    name = forms.CharField(max_length=150)
    organization = forms.ModelChoiceField(queryset=Organization.objects.all(), required=True)

    def save(self, commit=True):
        user = super().save(commit=False)
        new_organization_name = self.cleaned_data.get('new_organization')
        
        if new_organization_name:
            organization, created = Organization.objects.get_or_create(name=new_organization_name)
            user.organization = organization
        elif self.cleaned_data.get('organization'):
            user.organization = self.cleaned_data.get('organization')
        
        if commit:
            user.save()
        return user

class CustomUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('Personal info', {'fields': ('name', 'organization', 'user_type')}),
        ('Permissions', {
            'fields': ('credential_sent', 'is_active', 'is_staff', 'is_superuser',), # 'groups', 'user_permissions'
        }),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'name', 'organization', 'new_organization', 'user_type', 'password1', 'password2'),
        }),
    )
    list_display = ('username', 'name', 'organization', 'user_type', 'is_staff')
    readonly_fields = ('date_joined', 'last_login')
    search_fields = ('username', 'name', 'organization__name')
    ordering = ('username',)
    add_form = CustomUserCreationForm

class OrganizationAdmin(admin.ModelAdmin):
    list_display = ['name']
    search_fields = ['name']

admin.site.register(CustomUser, CustomUserAdmin)
admin.site.register(Organization, OrganizationAdmin)