I have a Django model with a ManyToMany field called images, and a simple ModelForm for that model.
I’m trying to post data using jQuery and a very basic UpdateView.
The model’s field
images = models.ManyToManyField(
RawImage,
null = True,
)
The form
class PublicDataPoolForm(forms.ModelForm):
error_css_class = 'error'
class Meta:
model = PublicDataPool
The UpdateView
class PublicDataPoolAddDataView(AjaxableResponseMixin, UpdateView):
model = PublicDataPool
form_class = PublicDataPool_ImagesForm
@method_decorator(user_passes_test(lambda u: user_has_active_subscription(u)))
def dispatch(self, *args, **kwargs):
return super(PublicDataPoolAddDataView, self).dispatch(*args, **kwargs)
The jQuery posting the data
$.ajax({
type: 'post',
dataType: 'json',
url: '/rawdata/publicdatapools/' + pk + '/add-data/',
data: {images: [1, 2]}
});
I get a ValidationError because the field images is required. If I print my request.POST in my UpdateView, I get this:
<QueryDict: {u'images[]': [u'1', u'2']}>
I believe the problem is with those [], because I’ve checked with another form that gets posted in a more traditional way, and the request.POST doesn’t have those [] in the field name.
Any idea what I’m missing?
You’ll want to set
jQuery.ajaxSettings.traditional = true;on page load so that jquery doesn’t append the[]to the key.Source:
http://forum.jquery.com/topic/jquery-post-1-4-1-is-appending-to-vars-when-posting-from-array-within-array#14737000000691277