Django 1.10 pass form object into template

Question

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

Template:

{{ form }} #  prints nothing

Views:

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

Form:

class EntertainerCheckboxForm(forms.Form):    
    class Meta:
        model = Entertainer
        fields = ['first_name',
                  'second_name',
                  'last_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 to Django 1.10 pass form object into template ( 2 )

  1. 2017-01-02 16:01

    In views.py:

    from myappname.forms import EntertainerCheckboxForm

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

    In template.html:

    {{myform}}
    
  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']
    

Leave a reply to - Django 1.10 pass form object into template

◀ Go back