Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get current view in template

How can I get the full name of the current view (my_app.views.index) in a template in Django 1.5?

With forms, I have an object called "view" in the template which I read using a template tag. But with DetailViews I doesn't see anything similar.

Is there a way using a custom template processor?

Thanks

EDIT

Situation 1:

  1. I retrieve a page, for example '/foo/bar/5/edit'.
  2. Django will call 'foo.views.editbar' with pk=5.
  3. This view renders an template 'foo/bar_form.html'

Situation 2:

  1. If I retrieve '/foo/bar/new'
  2. Django will call 'foo.views.newbar'
  3. This view renders the same template as above ('foo/bar_form.html')

How can I check in this template 'foo/bar_form.html', from which view it has been rendered? The result should be one of

  • 'foo.views.editbar'
  • 'foo.views.newbar'
like image 604
Dj Boris Avatar asked Sep 15 '25 05:09

Dj Boris


2 Answers

Type just in view

{% with request.resolver_match.view_name as view_name %}
    ...
    {{ view_name }}
    ...
{% endwith %}
like image 58
Evgeny A. Mamonov Avatar answered Sep 16 '25 20:09

Evgeny A. Mamonov


I'm not sure I completely understand the requirement, but take a look at inspect.stack.

inspect.stack()[1][3]
like image 34
Django Doctor Avatar answered Sep 16 '25 20:09

Django Doctor