I've read about the can_add_related feature here: https://code.djangoproject.com/ticket/9071
I tried using it this way:
def get_form(self, request, obj=None, **kwargs):
self.fields['person'].can_add_related = False
return super(OperationAdmin, self).get_form(request, obj, **kwargs)
But this throws a TypeError and I don't know how to solve this.
Can someone point me in the right direction?
Thank you.
Another approach, if you are defining an Inline model and use it in your admin, would be to overwrite the get_formset method:
from django.contrib import admin
class MyModelInline(admin.TabularInline):
model = MyModel
extra = 0
min_num = 1
max_num = 10
fields = [
'some_field'
]
def get_formset(self, request, obj=None, **kwargs):
fs = super().get_formset(request, obj, **kwargs)
fs.form.base_fields['some_field'].widget.can_add_related = False
fs.form.base_fields['some_field'].widget.can_change_related = False
fs.form.base_fields['some_field'].widget.can_delete_related = False
return fs
This is probably coming in late. But for other viewers reference,
def get_form(self, request, obj=None, **kwargs):
form = super(ProductAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['category'].widget.can_add_related = False
return form
can_add_related
seems to be an attribute on the widget, not the field, so try:
self.fields['person'].widget.can_add_related = False
Alternative approach, with changing widget options *before* the form is instantiated:
class MyAdmin(django.contrib.admin.ModelAdmin):
def formfield_for_dbfield(self, *args, **kwargs):
formfield = super().formfield_for_dbfield(*args, **kwargs)
if hasattr(formfield, "widget"):
formfield.widget.can_add_related = False
formfield.widget.can_delete_related = False
formfield.widget.can_change_related = False
else:
pass # this relation doesn't have an admin page to add/delete/change
return formfield
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