Django中的隐藏字段不在clean_data中 [英] Hidden field in Django form not in cleaned_data

查看:216
本文介绍了Django中的隐藏字段不在clean_data中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个表单:

  class CollaboratorForm(forms.Form):
user = forms.CharField label =Username,max_length = 100)
canvas = forms.IntegerField(widget = forms.HiddenInput)
....
def clean_user(self):
user = self.cleaned_data ['user']
canvas = self.cleaned_data ['canvas']

在视图中,我只是调用

 如果form.is_valid():

我收到错误:

  KeyError at / canvas / 1 / add-collaborator / 
'canvas'

根据firebug的价值正在发布,它似乎没有使我的清洁功能。我做错了吗?



编辑:发布数据

 画布1 
csrfmiddlewaretoken 2cb73be791b32ca9a41566082c804312
用户名称

EDIT2:我也愿意拿一个可以告诉我如何将主键发送到clean_user函数的答案,其中主键是上面的示例url中的/ 1 /。调用的视图中的函数是:

  def canvas_add_collaborator(request,pk):

所以我想将pk发送到clean_user函数,这将解决我的问题,不需要隐藏的字段。

解决方案

您需要将方法名称更改为clean(),而不是clean_user()。如果您只是验证用户字段,'canvas'不在clean_data中。


I have this form:

class CollaboratorForm(forms.Form):
    user = forms.CharField(label="Username",max_length=100)
    canvas = forms.IntegerField(widget=forms.HiddenInput)
    ....
    def clean_user(self):
        user = self.cleaned_data['user']
        canvas = self.cleaned_data['canvas']

In the view I'm simply calling

if form.is_valid():

I get the error:

KeyError at /canvas/1/add-collaborator/
'canvas'

According to firebug the value is posting, it's just doesn't seem to be making it to my clean function. Am I doing it wrong?

EDIT: Post data

canvas  1
csrfmiddlewaretoken 2cb73be791b32ca9a41566082c804312
user    username

EDIT2: I would also be willing to take an answer that could tell me how to send the primary key to the clean_user function, where the primary key is the /1/ in the example url above. The function in the view that is called is:

def canvas_add_collaborator(request, pk):

So I would want to send the pk to the clean_user function which would solve my problem by not needing the hidden field.

解决方案

You need to change the method name to clean(), not clean_user(). 'canvas' is not in the cleaned_data if you are just validating the user field.

这篇关于Django中的隐藏字段不在clean_data中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆