📜 ⬆️ ⬇️

Django Admin Actions - actions with an intermediate page

Hey. Useful thing action in the admin! I want to share how you can make an action that after selecting the elements will send the user to an intermediate page so that you can do something special with these elements. Example? For example, you have an online store, a table of products. You want to transfer part of the goods from one section (book) to another (technical books). Select the books you need, select the action “Move to another section”, click apply, go to the intermediate page, select the desired section and click save. Great? Let's try.

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 ID of the selected items. Django will pick them up from the POST request and make a Queryset for which we will do our actions (see the code below).

Our action is 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 an action in the class ProductAdmin:

 actions = [move_to_category,] 

And create a template to show it all.

 {% extends "admin/base_site.html" %} {% block content %} <form action="" method="post">{% csrf_token %} {{ form }} <p>      :</p> <ul>{{ items|unordered_list }}</ul> <input type="hidden" name="action" value="move_to_category" /> <input type="submit" name="apply" value="" /> </form> {% endblock %} 

That's all. In this way you can do very, very much all sorts of important, necessary and interesting things.

And finally, I want to bring screenshots from the working draft that show how it all works.

image

image

image

image

Good luck!

Source: https://habr.com/ru/post/140409/


All Articles