带有可选外键字段的 Django Formset 验证
使用 modelformset_factory
构建 ModelFormSet
并使用具有可选foreignkey的模型,如何创建空(null)关联以在该表单上进行验证?
这是一个示例代码:
### model
class Prueba(models.Model):
cliente = models.ForeignKey(Cliente, null = True)
valor = models.CharField(max_length = 20)
### view
def test(request):
PruebaFormSet = modelformset_factory(model = Prueba, extra = 1)
if request.method == 'GET':
formset = PruebaFormSet()
return render_to_response('tpls/test.html', {'formset' : formset},
context_instance = RequestContext(request))
else:
formset = PruebaFormSet(request.POST)
# dumb tests, just to know if validating
if formset.is_valid():
return HttpResponse('0')
else:
return HttpResponse('1')
在我的模板中,我只是调用呈现组合字段的 {{ form.cliente }} 方法,但是,我希望能够选择一个空的(标记为“------” ") 值,因为 FK 是可选的...但是当提交表单时,它不会验证。
这是正常行为吗?我如何使该字段跳过所需的验证?
Having a ModelFormSet
built with modelformset_factory
and using a model with an optional ForeignKey, how can I make empty (null) associations to validate on that form?
Here is a sample code:
### model
class Prueba(models.Model):
cliente = models.ForeignKey(Cliente, null = True)
valor = models.CharField(max_length = 20)
### view
def test(request):
PruebaFormSet = modelformset_factory(model = Prueba, extra = 1)
if request.method == 'GET':
formset = PruebaFormSet()
return render_to_response('tpls/test.html', {'formset' : formset},
context_instance = RequestContext(request))
else:
formset = PruebaFormSet(request.POST)
# dumb tests, just to know if validating
if formset.is_valid():
return HttpResponse('0')
else:
return HttpResponse('1')
In my template, i'm just calling the {{ form.cliente }} method which renders the combo field, however, I want to be able to choose an empty (labeled "------") value, as the FK is optional... but when the form gets submitted it doesn't validate.
Is this normal behaviour? How can i make this field to skip required validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在 cliente 中添加
blank = True
:null 与数据库相关,blank 用于前端验证。
Try adding
blank = True
to cliente:null is database related, blank is for front-end validation.