如何通过django admin中的操作请求用户输入?

时间:2014-08-10 23:02:44

标签: django django-models django-admin-filters

在我的代码中,我正在编写一个分组操作,我想问一下用户每组有多少人会喜欢,然后回复一个警告框,说明你有4个小组,在用户输入上。我如何在django admin中执行此操作,如何创建某种弹出窗口,询问他们想要放入群组中的人数? (我试图通过行动来实现这一目标)

admin.py:

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

2 个答案:

答案 0 :(得分:1)

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 / amount_per_form.html”包含以下内容:

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

 {% block content %}
 <form action="" method="post">
    {% csrf_token %}
    <input type="hidden" name="action" value="assign_new_manager" />
    {{ form }}
    <p>Apply for:</p>
    <ul>{{ items|unordered_list }}</ul>
    <input type="submit" name="apply" value="Apply" />
 </form>
 {% endblock %}

答案 1 :(得分:0)

我发现了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)

现在,在您的admin.py中定义该XForm

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"