Django Admin- disable Editing and remove “Save” buttons for a specific model

前端 未结 9 1291
眼角桃花
眼角桃花 2020-12-24 07:39

I have a Django Model which I wish to be only readonly. No adds and edits allowed.

I have marked all fields readonly and overridden has_add_permission in ModelAdmin

9条回答
  •  悲&欢浪女
    2020-12-24 08:00

    Updated answer using Django 1.8 (Python 3 syntax).

    There are three things to do:
    1) extend the admin change form template, adding an if to conditionally suppress the submit buttons
    2) override admin.ModelAdmin.change_view() and set a context var for the template if to read
    3) prohibit unwanted POST requests (from DOM hacking, curl/Postman)


    MyProject/my_app/templates/admin/my_app/change_form.html

    {% extends "admin/change_form.html" %}
    {% load admin_modify %}
    {% block submit_buttons_top %}{% if my_editable %}{% submit_row %}{% endif %}{% endblock %}
    {% block submit_buttons_bottom %}{% if my_editable %}{% submit_row %}{% endif %}{% endblock %}
    

    MyProject/my_app/admin.py (MyModelAdmin)

    def change_view(self, request, object_id, form_url='', extra_context=None):
      obj = MyModel.objects.get(pk=object_id)
      editable = obj.get_status() == 'Active'
    
      if not editable and request.method == 'POST':
        return HttpResponseForbidden("Cannot change an inactive MyModel")
    
      more_context = {
        # set a context var telling our customized template to suppress the Save button group
        'my_editable': editable,
      }
      more_context.update(extra_context or {})
      return super().change_view(request, object_id, form_url, more_context)
    

提交回复
热议问题