django表单__init__不包括字段

时间:2013-12-25 23:49:14

标签: python django validation django-forms django-admin

我为我的某个模型的管理页面做了一个自定义操作,其中权限可以授予所有选定的对象。有一个中间页面,显示要授予权限的用户的多字段字段。

整个行动,从开始到结束,工作正常,除非我遇到与'南方'的一些(无关)问题。作为修复,我必须在表单声明中包含__init__。但是,现在,中间流中的用户和所选对象正确加载,但单击“Okay”按钮后表单无法验证。

根据我调试的内容,当我使用if request.POST.get('post'):时,单击OK后它不会发回POST。当我使用if request.method == 'POST':时,它会在显示表单时发送POST但单击“确定”后,表单将失败is_valid()测试,因为缺少字段。

当我不使用__init__

时,相同的代码完美无缺
from models import ClientInfo
from customauth.models import ZenatixUser


class SelectUserForm(forms.Form):
    _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)

    def __init__(self, initial, *args, **kwargs):
        super(SelectUserForm, self).__init__(*args, **kwargs)
        try:
            clientObj = ClientInfo.objects.all()[:1].get()
            client = clientObj.corp
            client_name = client.shortName
            client_id = client.cID
            userList = ZenatixUser.objects.filter(corp__cID=client_id)
            #user = forms.ModelMultipleChoiceField(userList, label=client_name + ' users ')
            self.fields['user'] = forms.ModelMultipleChoiceField(userList, label=client_name + ' users ')
            self._selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
        except ClientInfo.DoesNotExist:
            raise Exception('Please add a client info object to the client')


def grant_read_permission(modeladmin, request, queryset):
    opts = modeladmin.model._meta
    app_label = opts.app_label

    form = None

    #if request.method == 'POST':
    if request.POST.get('post'):
        print 'POST'
        form = SelectUserForm(request.POST)
        print form.errors

        if form.is_valid():
            print 'Valid'
            users = form.cleaned_data['user']
            stream_count = queryset.count()
            user_count = len(users)
            for stream in queryset:
                for user in users:
                    print user, stream
                    assign_perm('read_stream', user, stream)

            plural = ['', '']
            if user_count != 1:
                plural[0] = 's'
            if stream_count != 1:
                plural[1] = 's'

            modeladmin.message_user(request, "Successfully granted read permission to %d user%s on %d stream%s." % (
                user_count, plural[0], stream_count, plural[1]))

            return None

    if not form:
        form = SelectUserForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

    stream_list = []
    for stream in queryset:
        stream_list.append(stream.path)

    title = _("Are you sure?")

    context = {
        "title": title,
        "objects_name": objects_name,
        'queryset': stream_list,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'tag_form': form,
    }

    return render_to_response("admin/grant_read_permission.html", context,
                              context_instance=template.RequestContext(request))

1 个答案:

答案 0 :(得分:1)

你已经从args / kwargs列表中提取了一个你称之为initial的参数,并且你没有将它传递给超级调用。实际上,第一个位置参数是表单数据,没有它,表单永远不会有效。从方法定义中删除该名称。