I am using django and dajax and I am trying to validate an item that has a many-to-many field. I am using the django forms to create the form for this model. When I submit the form with a submit button and have at least 1 to x number of items selected in the selectbox, the model gets validated. When I use dajax, the model will only validate if I have atleast 2 of the items in the select box are selected.
Does anyone know why this would happen?
Model
#Hints
class Hint(models.Model):
title = models.TextField(max_length=200)
body = models.TextField()
industryType = models.ManyToManyField(IndustryType)
screen = models.ManyToManyField(Screen)
#Creates form for a hint
class HintForm(ModelForm):
class Meta:
model = Hint
#widgets = {'industryType': CheckboxSelectMultiple, 'screen': CheckboxSelectMultiple }
industryType = ModelMultipleChoiceField(queryset=IndustryType.objects.all(),
widget=CheckboxSelectMultiple())
Template:
<form id="hintForm" action="." method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit"/>
</form>
<input type="button" onclick="send_form();" value="Add Hint" />
<script>
function send_form(){
data = $('#hintForm').serializeObject();
// jQuery
// If you are using jQuery, you need this form->object serializer
// https://github.com/cowboy/jquery-misc/blob/master/jquery.ba-serializeobject.js
alert(data['screen'])
Dajaxice.THE.send_form(Dajax.process,{'hintform':data});
return(false)
}
</script>
Code in the View
def addHint(request):
if request.method == 'POST': # If the form has been submitted...
form = HintForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
#savedHint = form.save()
#messages.success(request, '{0} has been added.'.format(savedHint))
print "Success"
else:
form = HintForm() # An unbound form
return render_to_response('manage/screens/form.html', {
'form': form, 'breadcrumName' : 'Add Screen' }, context_instance=RequestContext(request))
AJAX.py
@dajaxice_register
def send_form(request, hintform):
dajax = Dajax()
form = HintForm(hintform)
print form
if form.is_valid():
dajax.alert("This form is_valid")
else:
dajax.alert("Not Valid")
return dajax.json()
I had problems serializing form data using Dajax until I switched to a different serialize object function. I realize this isn’t a comprehensive and tested answer to your question but you could give this alternate serialize function a shot:
https://github.com/danheberden/serializeObject
Maybe also do some firebug / console output for your serialized form object to see if/how it’s being munged.
Cheers