Django Formset validation with an optional ForeignKey field
Posted
by Camilo Díaz
on Stack Overflow
See other posts from Stack Overflow
or by Camilo Díaz
Published on 2010-05-10T20:51:14Z
Indexed on
2010/05/10
20:54 UTC
Read the original article
Hit count: 567
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?
© Stack Overflow or respective owner