Last active
November 9, 2020 20:57
-
-
Save ohld/c427cf08ae84049e998bab1d4fe16f33 to your computer and use it in GitHub Desktop.
Django Admin action with intermediate page example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# your_app/admin.py | |
# ... imports | |
@admin.register(User) | |
class UserAdmin(admin.ModelAdmin): | |
actions = ['broadcast'] # register method as action | |
def broadcast(self, request, queryset): | |
if 'apply' in request.POST: # if user pressed 'apply' on intermediate page | |
# Cool thing is that params will have the same names as in forms.py | |
broadcast_message_text = request.POST["broadcast_text"] | |
bot_id = request.POST["bot"] | |
# Get data from models using the params - maybe not the best way, sorry | |
bot_token = Bot.objects.filter(id=bot_id).first().token | |
user_ids = [u.user_id for u in queryset] | |
# Run background task that will send broadcast messages | |
broadcast_message.delay(bot_token, user_ids, broadcast_message_text) | |
# Show alert that everything is cool | |
self.message_user(request, "Broadcasting of %s messages has been started" % len(user_ids)) | |
# Return to previous page | |
return HttpResponseRedirect(request.get_full_path()) | |
# Create form and pass the data which objects were selected before triggering 'broadcast' action | |
# We create an intermediate page right here | |
form = BroadcastForm(initial={'_selected_action': queryset.values_list('id', flat=True)}) | |
# We need to create a template of intermediate page with form - but this is really easy | |
return render(request, "admin/broadcast_message.html", {'items': queryset, 'form': form}) |
They could be just regular Django objects which were declared in models.py file.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what should the form look like? E.g. what should be the type of items field?