Search code examples
djangoformstemplatesviewdjango-crispy-forms

Django: Is it possible to exclude fields in view?


I need to exclude some of my form's fields in the view. I know it is possible to do in the actual form with .exclude function, but in that case I'd need to make one form for each case. I can't do this in the template because I'm using crispy_forms.helper, calling it in the template with {% crispy form %}, otherwise I would iterate over fields and exclude which I need.

I would need to do something like:

form = ArtiForm(instance=Articulo.objects.get(codigo=arti), filter_on=request.session['codEmp']).exclude(field)

But exclude is not a form attr in view. Any way to handle this?


Solution

  • A form has a fields dictionary which is modifiable. So you can do:

    form.pop(field)
    

    after instantiating it but before calling is_valid().