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.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.