19
No, and it would be a bad idea. To directly refer to a view function name from the template introduces overly tight coupling between the view layer and the template layer.
A much better solution here is Djangoβs template inheritance system. Define a common parent template, with a block for the (small) area that needs to change in each viewβs version. Then define each viewβs template to extend from the parent and define that block appropriately.
36
Since Django 1.5, the url_name
is accessible using:
request.resolver_match.url_name
Before that, you can use a Middleware for that :
from django.core.urlresolvers import resolve
class ViewNameMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
url_name = resolve(request.path).url_name
request.url_name = url_name
Then adding this in MIDDLEWARE_CLASSES, and in templates I have this:
{% if request.url_name == "url_name" %} ... {% endif %}
considering a RequestContext(request) is always passed to the render function. I prefer using url_name for urls, but one can use resolve().app_name and resolve().func.name, but this doesnβt work with decorators β the decorator function name is returned instead.
- [Django]-Django index page best/most common practice
- [Django]-How to update() a single model instance retrieved by get() on Django ORM?
- [Django]-Is there a way to loop over two lists simultaneously in django?
7
If your naming is consistent in your urls.py and views.py, which it should be, then this will return the view name:
{{ request.resolver_match.url_name }}
Be sure to apply some context to it when you call it in the template. For example, I use it here to remove the delete button from my detail view, but in my update view the delete button will still appear!
{% if request.resolver_match.url_name != 'employee_detail' %}
- [Django]-Running a specific test case in Django when your app has a tests directory
- [Django]-How to get the ID of a just created record in Django?
- [Django]-What is more efficient .objects.filter().exists() or get() wrapped on a try
2
Since Django 1.5 you can access an instance of ResolverMatch through request.resolver_match.
The ResolverMatch gives you the resolved url name, namespace, etc.
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-Using Python's os.path, how do I go up one directory?
- [Django]-Check if celery beat is up and running
1
one simple solution is :
def view1(req):
viewname = "view1"
and pass this viewname to the template context
def view2(req):
viewname = "view2"
and pass this viewname to the template context
in template access the viewname as
{{viewname}}
and also you can use this in comparisons.
- [Django]-How to do a HTTP DELETE request with Requests library
- [Django]-How can I programmatically obtain the max_length of a Django model field?
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
1
This sounds like the perfect example of a generic view that you can set up.
See the following resources:
- Django Book β Chapter 11: Generic Views
- Django Docs -Tutorial: Chapter 4
- Django Docs β Generic Views
These links should help you simplify your views and your templates accordingly.
- [Django]-Sending JSON using the django test client
- [Django]-Django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6)
- [Django]-Automatically create an admin user when running Django's ./manage.py syncdb
1
Iβm working on this for a help-page system where I wanted each view to correspond to a help-page in my cms with a default page shown if no help page was defined for that view. I stumbled upon this blog where they use a template context processor and some python inspect magic to deduce the view name and populate the context with it.
- [Django]-How can I restrict Django's GenericForeignKey to a list of models?
- [Django]-Unique BooleanField value in Django?
- [Django]-Django ignores router when running tests?
1
If youβre using Class Based Views, you most likely have a view
variable you can access.
You can use several methods from that to determine which view has been called or which template is being rendered.
e.g.
{% if view.template_name == 'foo.html' %}
# do something
{% else %}
# other thing
{% endif %}
Another option is to take out the piece of the template where you need something to change and make it into a snippet and then use {% include 'my_snippet.html' with button_type = 'bold' %}
in your templates, sending arbitrary values to the snippet so it can determine what to show / how to style itself.
- [Django]-Temporarily disable auto_now / auto_now_add
- [Django]-Django DateField default options
- [Django]-Django migration with uuid field generates duplicated values
1
In your template, you can access the current view instance like this:
{{ view }}
Define class_name
method in your view
class ExampleView(FormView):
...
def class_name(self):
return self.__class__.__name__
You can get the class name of the current view in a template like this:
{{ view.class_name }}
{% if view.class_name == "ExampleView" %} ... {% endif %}
- [Django]-How to repeat a "block" in a django template
- [Django]-Easily rename Django project
- [Django]-Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found
0
Most generic views β if not all β inherits the ContextMixin
which adds a view
context variable that points to the View instance.
- [Django]-Python vs C#/.NET β what are the key differences to consider for using one to develop a large web application?
- [Django]-Identify the changed fields in django post_save signal
- [Django]-Consolidating multiple post_save signals with one receiver
-1
Why not trying setting up a session cookie, then read the cookie from your template.
on your views set cookies
def view1(request):
...
#set cookie
request.session["param"]="view1"
def view2(request):
request.session["param"]="view2"
then in your ONE template check something like..
{% ifequal request.session.param "view1" %}
... do stuff related to view1
{% endifequal %}
{% ifequal request.session.param "view2" %}
... do stuff related to "view2"
{% endifequal %}
Gath
- [Django]-Django select_related β when to use it
- [Django]-Google Static Maps URL length limit
- [Django]-Django "get() got an unexpected keyword argument 'pk'" error