Fusion
Fusion

Reputation: 5472

Django 1.10 pass form object into template

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?

Upvotes: 1

Views: 1712

Answers (2)

Jan Giacomelli
Jan Giacomelli

Reputation: 1339

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}}

Upvotes: 0

narendra-choudhary
narendra-choudhary

Reputation: 4826

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']

Upvotes: 5

Related Questions