newToCoding
newToCoding

Reputation: 1

How to pass list of Django form field names to template?

I have a very basic form:

class NavigationForm(forms.Form):
    NavSelection1 = forms.TextInput()

In my view I want to pass a list to the template:

form = NavigationForm()
context['formfields'] = [i for i in form.fields]
return render(request, "page.html", context)

I am hoping to be able to use:

{% for i in formfields %}
    {{i}}
{% endfor %}

But it returns nothing.

{{formfields}}

Alone returns an empty list

[]

I feel like I'm missing something simple but I'm stumped at the moment. Any help would be appreciated!

Upvotes: 0

Views: 881

Answers (2)

newToCoding
newToCoding

Reputation: 1

For some reason the form didn't like TextInput()

I changed it to CharField() and it passes all the form information I was expecting.

Upvotes: 0

Imran Rahman
Imran Rahman

Reputation: 164

I've been doing forms like this

form = NavigationForm()
context['form'] = form
return render(request, "page.html", context)

Then in your template

{{form}}

Or maybe you want to do this

{% for field in form %}
    {{field}}
{% endfor %}

Hope this answers your question

Upvotes: 1

Related Questions