Reputation: 2587
Is it possible to set a template url from a view in Django?
i.e. I have form with a cancel button and I want to use that form on multiple views but the cancel url will be different depending on what view the form is used in.
view:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['app'] = 'sites'
context['view'] = 'site_list'
context['cancel_id'] = 'this may or may not be set'
return context
template:
{% if cancel_id %}
<a href="{% url 'app:view' cancel_id %}" class="btn btn-primary">Cancel</a>
{% else %}
<a href="{% url 'app:view' %}" class="btn btn-primary">Cancel</a>
{% endif %}
Upvotes: 1
Views: 47
Reputation: 47374
You can just evaluate url at the view side using reverse
and pass it to the template:
in view:
from django.urls import reverse
context['cancel_url'] = reverse('app:view', args=[cancel_id])
return context
in template:
<a href="{{ cancel_url }}" class="btn btn-primary">Cancel</a>
Upvotes: 2