Remove “add another” in Django admin screen

后端 未结 10 606
孤独总比滥情好
孤独总比滥情好 2020-12-05 13:34

Whenever I\'m editing object A with a foreign key to object B, a plus option \"add another\" is available next to the choices of object B. How do I remove that option?

10条回答
  •  不知归路
    2020-12-05 14:15

    Look at django.contrib.admin.options.py and check out the BaseModelAdmin class, formfield_for_dbfield method.

    You will see this:

    # For non-raw_id fields, wrap the widget with a wrapper that adds
    # extra HTML -- the "add other" interface -- to the end of the
    # rendered output. formfield can be None if it came from a
    # OneToOneField with parent_link=True or a M2M intermediary.
    if formfield and db_field.name not in self.raw_id_fields:
        formfield.widget = widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field.rel, self.admin_site)
    

    I think your best bet is create subclass of ModelAdmin (which in turn is a subclass of BaseModelAdmin), base your model on that new class, override formfield_fo_dbfield and make it so that it won't/or will conditionally wrap the widget in RelatedFieldWidgetWrapper.

    One could argue that if you have a user that doesn't have rights to adding related objects, the RelatedFieldWidgetWrapper should not display the add link? Maybe this is something that is deserving of mention in Django trac?

提交回复
热议问题