Reputation: 1575
How can i correctly use add_form
in admin panel when class is inherited from admin.ModelAdmin
. I find out the hack with overriding get_form
method where you can dynamically change form
to add_form
value. With current approach i'm getting this error
formsets, inline_instances = self._create_formsets(request, form.instance, change=False)
AttributeError: 'UserForm' object has no attribute 'instance'
form.py
class AddCustomProductForm(forms.Form):
users = forms.ChoiceField(
label='Select a Profile',
required=True,
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["users"].choices = CustomUser.objects.all()
admin.py
class PostAdmin(admin.ModelAdmin):
list_display = ('email', 'created', 'company_id',)
add_form = AddCustomProductForm
form = CustomProductForm
fieldsets = (
(None, {"fields": ("users")}),
)
def get_form(self, request, obj=None, **kwargs):
defaults = {}
if obj is None:
defaults['form'] = self.add_form
defaults.update(kwargs)
return super().get_form(request, obj, **defaults)
Upvotes: 1
Views: 1254
Reputation: 141
You need a ModelForm, where you take the values directly from a Model( in this case ModelAdmin) in a form.
https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/
The other way is make "your" admin panel.
Upvotes: 1