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!