Django形成ChoiceField,导致表单验证失败

时间:2014-03-13 20:07:33

标签: django forms python-3.x

我有以下内容:

desig = []
class New_user_form(UserCreationForm):
    desig = forms.ChoiceField(choices=desig)
    def acquire_groups(self):
        g = Group.objects.all()
        for k in g:
             desig.append((k.name, k.name))
        print(desig)

    def save(self, commit=True):
         user = super(UserCreationForm, self).save(commit=False)
         user.set_password(self.cleaned_data["password1"])
         designation = self.cleaned_data["desig"]
         print("New_user_form save : Designation :", designation)
         if commit:
              user.save()
              g = Groups.objects.filter(name=designation)
              print("acquired group", g[0].name)
              user.groups.add(g)
         return user

以下是我的观点:

def register_user(request):
    if request.method == 'POST':
        form = New_user_form(request.POST)
        if form.is_valid():
            print("Form Validated")
            new_user = form.save()
            HttpResponse("Success")
        else:
            HttpResponse("Invalid Form")
    else:
        form = New_user_form()
        form.acquire_groups()
        g = Group.objects.all()
        desig = []
        for k in g:
            desig.append(k.name)
        args = {}
        args.update({'user':request.user.username,
                     'form':form,
                     'STATIC_URL':settings.STATIC_URL,
                     'desig': desig,})
        return render_to_response('register.html', args)

html template

我曾尝试多次保存表单,但始终无法验证。我不明白为什么选择字段失败。我可以使用没有选择字段的表单。但我想使用选择字段将新用户添加到现有组。 我不明白为什么表格无效。

编辑:我改变了我的表格如下:

class New_user_form(UserCreationForm):
    email = forms.EmailField(required=True)
    desig = []
    def __init__(self, **kwargs):
        u = UserCreationForm.__init__(self, kwargs)
        try:
            if kwargs['desig_group']:
                print("desig_group instantiated. Found kwargs = ", kwargs['desig_group'])
            else:
                print("desig_group not instantiated")
         except (AttributeError, KeyError) as ex:
            for g in Group.objects.all():
                self.desig.append((g.name, g.name))
                print("desig : ", self.desig)
                desig_group = forms.ModelChoiceField(queryset=Group.objects.all())

          def save(self, commit=True):
              user = super(UserCreationForm, self).save(commit=False)
              user.set_password(self.cleaned_data["password1"])
              user.email = self.cleaned_data["email"]
              designation = self.cleaned_data["desig_group"]
              print("New_user_form save : Designation :", designation)
              if commit:
                  user.save()
                  g = Groups.objects.filter(name=designation)
                  print("acquired group", g[0].name)
                  user.groups.add(g)
              return user

我现在改变了我的观点:

def register_user(request):
    if request.method == 'POST':
        print("request.POST = ", request.POST)
        form = New_user_form(**request.POST)
        print("form bound: ", form.is_bound)
        print("Form bool: ", bool(form.errors))
        if form.is_valid():
            print("Form Validated")
            new_user = form.save()
            return HttpResponse("Added new user")
        else:
            print("Form is invalid")
            HttpResponse("Invalid form submission.")
    else:
        form = New_user_form()
        g = Group.objects.all()
        desig = []
        for k in g:
            desig.append(k.name)
        args = {}
        args.update(csrf(request))
        args.update({'user':request.user.username,
                     'form':form,
                     'STATIC_URL':settings.STATIC_URL,
                     'desig': desig,})
        return render_to_response('emp_users/register.html', args)

有了这个,我的表单没有通过验证,但所有必需的数据都是在POST中到达的。 我现在只需知道如何验证它。

form.cleaned_data['desig_group']

返回KeyError,但POST在其querrydictionary

中具有该值

以下是我的帖子:

request.POST dump

1 个答案:

答案 0 :(得分:0)

初始化表单后,无法设置选项。相反,只需设置选项:

# forms.py
class New_user_form(UserCreationForm):
    desig = forms.ModelChoiceField(queryset=Group.objects.all())
    ...


# views.py
def register_user(request):
    form = New_user_form(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            print("Form Validated")
            new_user = form.save()

    args = {}
    args.update({'user':request.user.username,
        'form':form, 'STATIC_URL':settings.STATIC_URL,
        'desig': desig,})
    return render_to_response('register.html', args)