我正在使用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()
答案 0 :(得分:0)
我在使用Dajax序列化表单数据时遇到问题,直到我切换到不同的序列化对象函数。我意识到这不是一个全面且经过测试的答案,但你可以给这个备用序列化功能一个镜头:
https://github.com/danheberden/serializeObject
也许还会对序列化表单对象执行一些firebug / console输出,以查看它是否/如何被激活。
干杯