Django Admin Actions - Intermediate Page Actions
Hey. A useful action piece in the admin panel! I want to share how you can make an action which, after selecting elements, will send the user to an intermediate page so that something special can be done with these elements. Example? For example, you have an online store, a table of goods. You want to transfer part of the goods from one section (books) to another (technical books). We select the necessary books, select the “Transfer to another section” action, click apply, go to the intermediate page, select the desired section and click save. Is it great? Let's try.
We describe the form:
Mysterious field _select_action , yes? There will be the ID of the selected items. Django will then pick them up from the POST request and make them a Queryset for which we will do our actions (see code below).
Our action is as always a method. Let's call it move_to_category.
We declare the action in the ProductAdmin class:
And create a template to show it all
That's all. In this way, you can do a very, very many all sorts of important, necessary and interesting things.
And finally, I want to give screenshots from a working draft that show how it all works.




Good luck
We describe the form:
class ChangeCategoryForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
category = forms.ModelChoiceField(queryset=Category.objects.all(), label=u'Основная категория')
Mysterious field _select_action , yes? There will be the ID of the selected items. Django will then pick them up from the POST request and make them a Queryset for which we will do our actions (see code below).
Our action is as always a method. Let's call it move_to_category.
def move_to_category(modeladmin, request, queryset):
form = None
if 'apply' in request.POST:
form = ChangeCategoryForm(request.POST)
if form.is_valid():
category = form.cleaned_data['category']
count = 0
for item in queryset:
item.category = category
item.save()
count += 1
modeladmin.message_user(request, "Категория %s применена к %d товарам." % (category, count))
return HttpResponseRedirect(request.get_full_path())
if not form:
form = ChangeCategoryForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
return render(request, 'catalog/move_to_category.html', {'items': queryset,'form': form, 'title':u'Изменение категории'})
move_to_category.short_description = u"Изменить категорию"
We declare the action in the ProductAdmin class:
actions = [move_to_category,]
And create a template to show it all
{% extends "admin/base_site.html" %}
{% block content %}
{% endblock %}
That's all. In this way, you can do a very, very many all sorts of important, necessary and interesting things.
And finally, I want to give screenshots from a working draft that show how it all works.




Good luck