views:

170

answers:

1

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?

+3  A: 

Try adding blank = True to cliente:

cliente = models.ForeignKey(Cliente, null = True, blank = True)

null is database related, blank is for front-end validation.

jpartogi
Works like a charm. Thank you!
Camilo Díaz
No worries mate.
jpartogi