Skip to content Skip to sidebar Skip to footer

How To Use Can_add_related In Django Admin

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.fi

Solution 1:

This is probably coming in late. But for other viewers reference,

defget_form(self, request, obj=None, **kwargs):
    form = super(ProductAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['category'].widget.can_add_related = Falsereturn form

Solution 2:

can_add_related seems to be an attribute on the widget, not the field, so try:

self.fields['person'].widget.can_add_related = False

Solution 3:

Alternative approach, with changing widget options *before* the form is instantiated:

classMyAdmin(django.contrib.admin.ModelAdmin):

    defformfield_for_dbfield(self, *args, **kwargs):
        formfield = super().formfield_for_dbfield(*args, **kwargs)
        ifhasattr(formfield, "widget"):
            formfield.widget.can_add_related = False
            formfield.widget.can_delete_related = False
            formfield.widget.can_change_related = Falseelse:
            pass# this relation doesn't have an admin page to add/delete/changereturn formfield

Solution 4:

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


classMyModelInline(admin.TabularInline):
    model = MyModel
    extra = 0
    min_num = 1
    max_num = 10
    fields = [
        'some_field'
    ]

    defget_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 = Falsereturn fs

Post a Comment for "How To Use Can_add_related In Django Admin"