Django表单验证和管理操作

时间:2013-12-10 18:05:43

标签: python django forms django-admin

我正在开展一个项目,我想在其中对数据库中的项目进行批量更新。我认为最好利用Django Admin页面。

以下是我用来向用户显示所需操作的功能和相应表单:

class AssignIssueForm(forms.Form):
        _selected_action = forms.IntegerField(widget=forms.MultipleHiddenInput)
        issue = forms.ModelChoiceField(Issue.objects.filter(category__id = 1))


def assign_issue(self, request, queryset):
    logger_add_report = logging.getLogger('logview.add_report' )
    logger_add_report.debug("In assign_issue")

    if "apply" in request.POST:
        logger_add_report.debug(request)
        form = self.AssignIssueForm(request.POST)
        if form.is_valid():
            issue_number = form.cleaned_data["issue"]
            issue = Issue.objects.get(id = issue_number)

            for obj in queryset:
                obj.issue = issue
                issue.save()

            self.message_user(request, "Succesfully assign issue %s to the analyses" % (str(issue_number)))
            return HttpResponseRedirect(request.get_full_path())

        self.message_user(request, "Unsucessful!")
        return HttpResponseRedirect(request.get_full_path())

    form = self.AssignIssueForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})

    return render_to_response("assign_issue.html",  {
                                                        "analyses" : queryset,
                                                        "form" : form
                                                    },
                                                    context_instance=RequestContext(request) )

这是assign_issue.html文件:

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

{% block content %}

<p>Select an issue to apply: </p>

<form action="" method="post">{% csrf_token %}

    {{ form }}

    <p>The following analysis objects will be linked to the above issue:</p>

    <ul>
        {% for analysis in analyses %}
        <li>{{ analysis.id }}</li>
        {% endfor %}
    </ul>

    <input type="hidden" name="action" value="assign_issue" />
    <input type="submit" name="apply" value="Assign Issue" />
</form>

{% endblock %}

上面的代码显示了我想要的内容 - 我有一个下拉菜单来选择issue,而assign_issue.html上的表单会指向我的assign_issue函数。但是,问题在于表单验证。以下是从assign_issue.html传回来的request.POST的输出。

POST:<QueryDict: {u'action': [u'assign_issue'], u'_selected_action': [u'138912', u'138911', u'138910'], u'csrfmiddlewaretoken': [u'*snipped*'], u'issue': [u'129'], u'apply': [u'Assign Issue']}>,

如果将此POST数据制作成表格 - 行form = self.AssignIssueForm(request.POST) - ,form.is_valid()调用将失败。谁能解释为什么会发生这种情况?是因为我在QueryDict中有值,比如csrfmiddlewaretoken和apply,它们不在表单中吗?

我这里的代码基于this tutorial

0 个答案:

没有答案