Skip to content

Commit

Permalink
Added chapter from custom button
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 23, 2018
1 parent f31fa65 commit fe5dc77
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
41 changes: 41 additions & 0 deletions docs/custom_button.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,43 @@
How to add a custom button to Django change view page?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

:code:`Villain` has a field called :code:`is_unique`::

class Villain(Entity):
...
is_unique = models.BooleanField(default=True)


You want to add a button on Villain change form page called "Make Unique", which make this Villain unique.
Any other villain with the same name should be deleted.

You start by extending the :code:`change_form` to add a new button.::

{% extends 'admin/change_form.html' %}

{% block submit_buttons_bottom %}
{{ block.super }}
<div class="submit-row">
<input type="submit" value="Make Unique" name="_make-unique">
</div>
{% endblock %}

Then you can override :code:`response_change` and connect your template to the :code:`VillainAdmin`.::

@admin.register(Villain)
class VillainAdmin(admin.ModelAdmin, ExportCsvMixin):
...
change_form_template = "entities/villain_changeform.html"


def response_change(self, request, obj):
if "_make-unique" in request.POST:
matching_names_except_this = self.get_queryset(request).filter(name=obj.name).exclude(pk=obj.id)
matching_names_except_this.delete()
obj.is_umique = True
obj.save()
self.message_user(request, "This villain is now unique")
return HttpResponseRedirect(".")
super().response_change()

.. image:: custom_button.png
2 changes: 1 addition & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Django Admin Cookbook
.Django Admin Cookbook
===========================================================

Django Admin Cookbook - How to do things with Django admin.
Expand Down
12 changes: 12 additions & 0 deletions heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,18 @@ class VillainAdmin(admin.ModelAdmin, ExportCsvMixin):
actions = ["export_as_csv"]

readonly_fields = ["added_on"]
change_form_template = "entities/villain_changeform.html"


def response_change(self, request, obj):
if "_make-unique" in request.POST:
matching_names_except_this = self.get_queryset(request).filter(name=obj.name).exclude(pk=obj.id)
matching_names_except_this.delete()
obj.is_umique = True
obj.save()
self.message_user(request, "This villain is now unique")
return HttpResponseRedirect(".")
super().response_change()


class VillainInline(admin.StackedInline):
Expand Down

0 comments on commit fe5dc77

Please sign in to comment.