Cannot hide “Save and add another” button in Django Admin

前端 未结 6 1391
余生分开走
余生分开走 2021-01-03 05:54

I would like to hide all the \"Save\" buttons in Django\'s Admin\'s Change Form, for a specific model, when certain conditions are met. Therefore, I override the chang

6条回答
  •  不知归路
    2021-01-03 06:36

    The other keys are checked for in the passed context except show_save_and_continue. Django always sets this directly.

    'show_save_and_add_another': (
            context['has_add_permission'] and not is_popup and
            (not save_as or context['add'])
        ),
    

    You can patch the submit_row template tag function to first check the context dictionary for show_save_and_add_another.

    @register.inclusion_tag('admin/submit_line.html', takes_context=True)
    def submit_row(context):
        """
        Display the row of buttons for delete and save.
        """
        change = context['change']
        is_popup = context['is_popup']
        save_as = context['save_as']
        show_save = context.get('show_save', True)
        show_save_and_continue = context.get('show_save_and_continue', True)
        show_save_and_add_another = context.get('show_save_and_add_another', False)
        ctx = Context(context)
        ctx.update({
            'show_delete_link': (
                not is_popup and context['has_delete_permission'] and
                change and context.get('show_delete', True)
            ),
            'show_save_as_new': not is_popup and change and save_as,
            'show_save_and_add_another': (
                context.get('show_save_and_add_another', None) or
                (context['has_add_permission'] and not is_popup and
                (not save_as or context['add']))
            ),
            'show_save_and_continue': not is_popup and context['has_change_permission'] and show_save_and_continue,
            'show_save': show_save,
        })
        return ctx
    

    Edit

    Steps to patch the "admin/submit_line.html" inclusion tag

    1. Create a templatetags folder at the same level of models.py and views.py

    2. Create __init__.py in the templatetags folder

    3. Copy django/contrib/admin/templatetags/admin_modify.py to templatetags/admin_modify.py.

    4. Overwrite submit_row function definition with the one above.

    Note that this is applicable for Django 2.0 and below.

    For recent Django versions, find a context mix that allows this expression to be False.e.g.

    has_add_permission and not is_popup and
    (not save_as or add) and can_save
    

    See values for the names used in the above expression.

提交回复
热议问题