Reputation: 329
First, what is currently working:
I have a form defined in forms.py
:
class EnrollForm(forms.Form):
course_id = forms.IntegerField(required=True)
def enroll(self):
print(self.cleaned_data)
I build said form in a view in views.py
:
class EnrollView(FormView):
template_name = 'core/enroll.html'
form_class = EnrollForm
success_url=''
def form_valid(self, form):
form.enroll()
return super().form_valid(form)
I display it in enroll.html
:
<form action="." method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Enroll" />
</form>
So, when I visit localhost:8000/core/enroll/
, I see the form in all its might:
However, when I attempt to include this file in another file using
{% include "core/enroll.html" %}
in another html file, that only displays the button while the {{ form }}
tag in enroll.html
doesn't resolve to anything and just silently fails, showing:
EDIT1: This is the file from which I am attempting to include the form:
<h1>{{ course.title }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<ul>
{# reverse lookup on codes with course foreignkey relationship #}
{% for code in course.code_set.all %}
<li>{{ code.code }}</li>
{% endfor %}
</ul>
{% include "core/enroll.html" %}
Upvotes: 0
Views: 1002
Reputation: 2159
So here is the thing. When you visit localhost:8000/core/enroll/ django calls the view EnrollView where you define what the form is and pass it to context.
once in context, its html page, enroll.html, in this case knows what form variable is.
on the other hand when you visit another page, EnrollView is never gets called. the included partial {% include "core/enroll.html" %}, tries to render the form but does not know what form variable is.
The view which is rendering the html page in question (where you want to see the form, but can not) should add EnrollForm in the context.
context['form'] = EnrollForm()
something like above line. Then you should be able to see form.
Upvotes: 2