'How to display extra context and form fields at the same time on django template using class based view?
I am trying to display some extra context on the page, but when I adding get_context_data method it is displayed context but not a forms fields. This is because when I click ulr that triggers view below there is get method by default or prior to forms fields? I don't understand why forms disappear when this method present in SolutionCreate view, indeed all context data displayed
template
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-sm">
<form action="" method="POST">
<table>
{% csrf_token %}
{{ form.as_p }}
</table>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
<div class="col-sm">
{{ context }}
<h5>Problem:</h5>
{% for pr in prb %}
<h5>Problem: {{ pr.title }}</h5>
<h6>Description</h6>
<li class="list-group-item">{{ pr.description }}</li>
<p>
</p>
<h6>Risks</h6>
<li class="list-group-item">{{ pr.risks }}</li>
<p>
</p>
<h6>Parts</h6>
<li class="list-group-item">{{ pr.parts }}</li>
<p>
</p>
<h6>Causes</h6>
<li class="list-group-item">{{ pr.causes }}</li>
<p>
</p>
<h6>Published</h6>
<li class="list-group-item">{{ pr.published }}</li>
<p>
</p>
<a href="{% url 'delete_problem' pr.pk %}"
class="btn btn-warning"
role="button"
aria-pressed="true">Delete</a>
<a href="{% url 'update_problem' pr.pk %}"
class="btn btn-warning"
role="button"
aria-pressed="true">Update</a>
<p>
</p>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
view
class SolutionCreate(CreateView):
model = Solution
template_name = 'analysis/create_solution.html'
fields = [
'problem',
'research',
'solutions',
'resources',
'plan',
'test'
]
def post(self, request, *args, **kwargs):
form = SolutionForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/saved/')
return render(request, self.template_name, {'form': form})
def get_context_data(self, *args, **kwargs):
prb = Problem.objects.select_related()
return {'prb': prb}
Solution 1:[1]
get_context_data is a method on the parent class. If you override it, you still need to call the parent method which is what adds the form to the context. You do this by calling super() inside your own method, to obtain the context data, and then add your own:
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['prb'] = Problem.objects.select_related()
return context
Refer to the documentation on adding extra context to see how you should use get_context_data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | solarissmoke |
