3

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'
2
  • what are you trying for?
    – Leandro
    Jun 19, 2013 at 21:01
  • Can you explain more your question? and if it's possible put code please Jun 19, 2013 at 21:01

3 Answers 3

22

Type just in view

{% with request.resolver_match.view_name as view_name %}
    ...
    {{ view_name }}
    ...
{% endwith %}
1

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

inspect.stack()[1][3]
2
  • Thanks! This would work, but it's a very dirty hack. Is there really no way to retrieve this information direcly in a middleware or templatetag?
    – Dj Boris
    Jun 20, 2013 at 18:59
  • 2
    not that I know of. I use this method so if you find one better please let me know :). Small guidance - just comment what it is doing so future you will not look puzzled at this odd code.
    – Rich Tier
    Jun 20, 2013 at 21:35
-3

Just set attribute to request object in view:

setattr(request, 'view', 'app.views.func')

and check this in template:

{% if request.view == 'app.views.func' %}
    do something
{% endif %}

It worked for me.

1
  • 1
    Why would you use setattr instead of getattr. Set will set the attribute to the value passed to it.
    – coler-j
    Nov 8, 2018 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.