我正在使用 django 和 dajax,并且正在尝试验证具有多对多字段的项目。我正在使用 django 表单为此模型创建表单。当我使用提交按钮提交表单并在选择框中选择了至少 1 到 x 个项目时,模型得到验证。当我使用 dajax 时,模型只会验证我是否选择了选择框中的至少 2 个项目。
有谁知道为什么会发生这种情况?
模型
#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())
模板:
<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>
视图中的代码
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()