Django表单中的隐藏字段不在cleaned_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']
在我只是调用的视图中,
if form.is_valid():
我得到了错误:
KeyError at /canvas/1/add-collaborator/
'canvas'
根据萤火虫的值正在发布,它似乎没有进入我的干净函数。我做错了吗?
编辑:发布数据
canvas 1
csrfmiddlewaretoken 2cb73be791b32ca9a41566082c804312
user username
EDIT2:我也愿意接受一个答案,可以告诉我如何将主键发送到 clean_user 函数,其中主键是上面示例网址中的 /1/ 。被调用的视图中的函数是:
def canvas_add_collaborator(request, pk):
所以我想将 pk 发送到 clean_user 函数,这将通过不需要隐藏字段来解决我的问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将方法名称更改为 clean(),而不是 clean_user()。如果您只是验证用户字段,则“canvas”不在 clean_data 中。
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.
我发现字段声明中的顺序很重要,因此如果您想在 clean_user 方法中访问clean_data['canvas'],则必须首先在字段中声明canvas。我已经在模型表单中对此进行了测试
I found that the order in the declaration of fields matters, so if you want to access cleaned_data['canvas'] in the clean_user method, you must declare canvas first in your fields. I have tested this in Model forms
我使用以下方法解决了我的问题(可能不是最好的方法,但有效):
然后在我看来:
也许不是最优雅的解决方案,但它现在有效。欢迎反馈。
I solved my problem (probably not the best way, but works) using this:
Then in my view:
Maybe not the most elegant solution, but it works for now. Feedback welcome.