0
我使用的是django和dajax,我試圖驗證具有多對多字段的項目。我正在使用django表單爲這個模型創建表單。當我使用提交按鈕提交表單並且在選擇框中至少選擇了1到x個項目時,模型會得到驗證。當我使用dajax時,只有在選擇了至少2個選擇框中的項目時,模型纔會生效。Django Dajax驗證多對多字段的模型
有誰知道爲什麼會發生這種情況?
型號
#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()
感謝toasterleavings,新的serializeObject腳本解決了我的問題! – mikes000 2012-07-23 14:12:29
我遇到了一個問題,如果只選擇了一個,複選框就無效。我有一個驗證問題:「輸入值的列表。」 – mikes000 2012-10-09 17:44:23
我通過改變serializeObject來解決它:http://jsfiddle.net/sy3d4/ – mikes000 2012-10-09 17:49:52