如何在django admin中请求用户输入一个动作?

fsi0uk1n  于 2023-01-06  发布在  Go
关注(0)|答案(2)|浏览(110)

在我的代码中,我正在写一个分组动作,我想问用户他们希望每个组有多少人,然后用一个警告框来回应,根据用户的输入,你有4个组。我该如何在django管理中做这个,我如何创建某种弹出窗口,询问他们希望加入一个组的人数?(我正尝试通过一个操作来实现这一点)
admin.py:

Def howmany (modeladmin, request, queryset):
      people = queryset.count()
      amount_per = [the number that the user inputs]
      Amount_of_groups = people/amount_per
jm81lzqq

jm81lzqq1#

我发现了一种更简单、更好的方法here
您只需要创建一个这样的操作表单。

from django.contrib.admin.helpers import ActionForm
from django import forms

class XForm(ActionForm):
    x_field = forms.ModelChoiceField(queryset=Status.objects.all(), required=False)

现在,在www.example.com中定义这个XFormadmin.py

class ConsignmentAdmin(admin.ModelAdmin):

    action_form = XForm
    actions = ['change_status']

    def change_status(modeladmin, request, queryset):
        print(request.POST['x_field'])
        for obj in queryset:
            print(obj)
    change_status.short_description = "Change status according to the field"
kpbwa7wx

kpbwa7wx2#

admin.py :

class MyAdmin(admin.ModelAdmin):

    def howmany(modeladmin, request, queryset):
        people = queryset.count()
        amount_per = [the number that the user inputs]
        Amount_of_groups = people/amount_per

        if 'apply' in request.POST:
            form = AmountPerForm(request.POST)

            if form.is_valid():
                amount_per = form.cleaned_data['amount_per']
                self.message_user(request, u'You selected - %s' % amount_per)
            return HttpResponseRedirect(request.get_full_path())
        else:
            form = AmountPerForm()

        return render(request, 'admin/amount_per_form.html', {
            'items': queryset.order_by('pk'),
            'form': form,
            'title': u'Your title'
            })

文件“admin/金额_per_form.html”包含类似于以下内容的内容:

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

 {% block content %}
 <form action="" method="post">
    {% csrf_token %}
    <input type="hidden" name="action" value="howmany" />
    {% for item in items %}
    <input type="hidden" name="_selected_action" value="{{ item.pk }}"/> {# thanks to @David Hopkins for highligting it #}
    {% endfor %}

    {{ form }}
    <p>Apply for:</p>
    <ul>{{ items|unordered_list }}</ul>
    <input type="submit" name="apply" value="Apply" />
 </form>
 {% endblock %}

相关问题