Django Formset validation with an optional ForeignKey field
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(mode开发者_如何学Cls.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?
Try adding blank = True
to cliente:
cliente = models.ForeignKey(Cliente, null = True, blank = True)
null is database related, blank is for front-end validation.
精彩评论