How to use can_add_related in Django Admin

后端 未结 3 1794
一个人的身影
一个人的身影 2020-12-19 01:39

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,          


        
相关标签:
3条回答
  • 2020-12-19 01:53

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

    self.fields['person'].widget.can_add_related = False
    
    0 讨论(0)
  • 2020-12-19 01:57

    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
    
    0 讨论(0)
  • 2020-12-19 02:13

    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
    
    0 讨论(0)
提交回复
热议问题