I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.
The extra fields appear on the form and they are sent in the POST request when uploading the form. The problem is they are not added to the cleaned_data
dictionary when I validate the form. How can I access them?
This answer may be too late for the original poster, but I thought it might help others. I had the same problem and I did notice that self.cleaned_data('artist_id') can be accessed in the clean() method, but not in the clean_artist().
When I added the extra fields in the 'fields' declaration of Meta, then it worked.
You should be able to access the self.cleaned_data('artist_id') in clean_artist().
First add the field in the form
Now while cleaning you data, you need to retrive the extra field from self.data NOT self.cleaned_data
Correct:
Wrong:
I had a very similar problem except it looked like I did all the required thing, but I was getting this error when Django was starting:
This was a silly mistake from me, I accidentally declared my field using a Widget class:
Instead of a Field class:
Not answering the question at hand here (which is answered well already), but might help others.
Ok I have resolved it. It seems that accessing the extra fields with cleaned_data['field_name'] raises a KeyError but using cleaned_data.get('field_name') works. That's weird because normal fields for the model can be accessed via cleaned_data['field_name'].
Update: No, it doesn't work. With get() it doesn't raise a KeyError but it sets a value of None because the extra fields are not in the cleaned_data dictionary.
Here is the code. In the templates there is an autocomplete, so in the form there is an "artist" field rendered as a CharField and an hidden IntegerField that will be autopopulated with the given artist id. In the clean_artist method I want to select the artist object and store it in the artist field of the form.
models.py
forms.py
It's possible to extend Django
ModelForm
with extra fields. Imagine you have a custom User model and thisModelForm
:Now, imagine you want to include an extra field (not present in your User model, lets say an image avatar). Extend your form by doing this:
Finally (given that the form has an
ImageField
), remember to includerequest.FILES
when instantiating the form in your view:Hope it helps. Good luck!
EDIT:
I was getting a "can only concatenate tuple (not "list") to tuple" error in AvatarProfileForm.Meta.fields attribute. Changed it to a tuple and it worked.
First, you shouldn't have artist_id and artist fields. They are build from the model. If you need some artist name, add artist_name field, that is CharField.
Furthermore, you are trying to retrieve something from cleaned_data inside clean value. There might not be data you need - you should use values from self.data, where is data directly from POST.