Hidden field in Django form not in cleaned_data

青春壹個敷衍的年華 提交于 2019-12-10 02:36:56

问题


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.


回答1:


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.




回答2:


I solved my problem (probably not the best way, but works) using this:

class CollaboratorForm(forms.Form):
    ....
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('canvas', None)
        super(CollaboratorForm, self).__init__(*args, **kwargs)

Then in my view:

def canvas_add_collaborator(request, pk):
    ....
    form.canvas = pk

Maybe not the most elegant solution, but it works for now. Feedback welcome.




回答3:


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



来源:https://stackoverflow.com/questions/8328763/hidden-field-in-django-form-not-in-cleaned-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!