Django 1.10 pass form object into template


I would like to pass my custom form into a template file.


{{ form }} #  prints nothing


class EntertainerDisplay(FormView):
    form_class = EntertainerCheckboxForm
    template_name = 'entertaining/custom_form.html'


class EntertainerCheckboxForm(forms.Form):    
    class Meta:
        model = Entertainer
        fields = ['first_name',

No matter what I do, form variable is never in View context, and therefore not sent into a template file. How can I pass form and its fields into form variable in a template file?

Show source
| django   | django-forms   2017-01-02 16:01 2 Answers

Answers ( 2 )

  1. 2017-01-02 16:01


    from myappname.forms import EntertainerCheckboxForm

    def my_form_view
        myform = EntertainerCheckboxForm()
        return render(request,'path/to/your/template', {'myform': myform})

    In template.html:

  2. 2017-01-02 16:01

    The error is in EntertainerCheckboxForm definition. It should be a subclass of forms.ModelForm, not forms.Form.

    Since you've defined EntertainerCheckboxForm as subclass for forms.Form and haven't added any form field manually, it doesn't render any form field because there is no field to render.

    The correct definition should be as follows:

    class EntertainerCheckboxForm(forms.ModelForm):    
        class Meta:
            model = Entertainer
            fields = ['first_name', 'second_name', 'last_name']
◀ Go back