Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created March 31, 2020 14:47
Show Gist options
  • Save DataGreed/7d87e2ccfa2c98310ef9655140439edf to your computer and use it in GitHub Desktop.
Save DataGreed/7d87e2ccfa2c98310ef9655140439edf to your computer and use it in GitHub Desktop.
Django admin action ith an intermidiate page with form example (this one uses django-push-notifications)
class ExtendedDeviceAdmin(DeviceAdmin):
actions = ("send_message", "send_bulk_message", "send_custom_message_bulk", "enable", "disable")
def send_custom_message_bulk(self, request, queryset):
form = None
# TODO: handle situation when results from multiple pages selected (or is it handled automatically in django 2?)
if 'apply' in request.POST: # if user pressed 'apply' on intermediate page
form = CustomPushMessageAdminForm(request.POST)
if form.is_valid():
message = form.cleaned_data['alert_body']
# check if alert body is a json and convert it to dict if it is
# if it's not, just leave it as a string
try:
message = json.loads(message)
except json.JSONDecodeError:
pass
extra = None
extra = form.extra_json
try:
extra = json.loads(extra)
except json.JSONDecodeError:
pass
# calls some actual method doing heavy work
self.send_messages(request, queryset, True, message_text=message, extra=extra)
# Show alert that everything is cool
self.message_user(request, "Sent custom messages")
# Return to previous page
# return None
return HttpResponseRedirect(request.get_full_path())
if not form:
form = CustomPushMessageAdminForm(initial={'_selected_action': queryset.values_list('id', flat=True)})
return render(request, "admin/custom_push_message.html", {'items': queryset, 'form': form})
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}">
{{ form.media }}
{% endblock %}
{% block coltype %}colMS{% endblock %}
{% block bodyclass %}{{ block.super }} dashboard{% endblock %}
{% block breadcrumbs %}{% endblock %}
{% block content %}
<div id="content-main">
<h1>Push notification structure</h1>
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="action" value="send_custom_message_bulk" />
<p>
<input type="submit" name="apply" value="apply"/>
</p>
</form>
</div>
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment