What's the simplest way to access the name of the current app within template code?
Alternatively, what's the simplest way to define a template variable to hold the name of the current app?
(The goal here is to minimize the number of places I need to edit if I rename an app.)
Since Django 1.5 there is a "resolver_match" attribute on the request object.
https://docs.djangoproject.com/en/dev/ref/request-response/
This contains the matched url configuration including "app_name", "namespace", etc.
https://docs.djangoproject.com/en/2.2/ref/urlresolvers/#django.urls.ResolverMatch
The only caveat is that it is not populated until after the first middleware passthrough, so is not available in process_request functions of middleware. However it is available in middleware process_view, views, and context processors. Also, seems like resolver_match is not populated in error handlers.
Example context processor to make available in all templates:
def resolver_context_processor(request):
return {
'app_name': request.resolver_match.app_name,
'namespace': request.resolver_match.namespace,
'url_name': request.resolver_match.url_name
}
There's a way to obtain an app name for a current request.
First, in your project's urls.py, considering your app is called 'main':
#urls.py
url(r'^', include('main.urls', app_name="main")),
Then, a context processsor:
#main/contexts.py
from django.core.urlresolvers import resolve
def appname(request):
return {'appname': resolve(request.path).app_name}
Don't forget to enable it in your settings:
#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"main.contexts.appname",)
You can use it in your template like any other variable: {{ appname }}.
Related
I want to include the same variables in all the views , to avoid repeating , i've been looking at django docs and found the generic display views and i tried it but it doesnt seems to work.
Any idea how to do this ?
Write a template context processor:
def add_foo(request):
return {'var': 'foo'}
Save this to a file, lets say custom_context.py, put it inside the same directory as your views.py.
Then, add it to your TEMPLATE_CONTEXT_PROCESSORS setting - make sure you keep the default ones, otherwise other functions may not work. You need to add the Python path, so add yourapp.custom_context.add_foo,
Now, whenever you return a RequestContext instance (you can do this by using the render shortcut, and all class based views automatically return a RequestContext instance); the variable var will be available in your templates, as {{ var }}.
Just looking for some guidance here on how to implement this concept in "Django fashion".
I am using dbsettings to define site level variables. On each request I want to check one of my site level variables and render a different response based on the value of that variable.
Now I realize I could easily accomplish this just by adding a simple if statement in each of my view functions, but I thought there may be a way I could apply this at a higher level?
Let me know if there is a way to "globalize" this functionality across all requests. Thanks.
Actually, what you really probably want is middleware, if the setting is going to affect the template that's chosen in the first place, or substantially affect the response. It is a good deal more flexible than using a template context processor, which is more appropriate if you simply want to add a couple variables to your context.
You create a middleware.py in your app, which might contain something like:
from django.conf import settings
class MyMiddleware(object):
def process_request(self, request):
request.my_app_setting = settings.MY_APP_SETTING
Don't forget to add your class to your MIDDLEWARE_CLASSES setting.
You can use custom template context processors for passing "global" context to your views.
To accomplish this, create a new contextprocessors.py somewhere in your application with code similar to the example below (all it has to do is return a dict). Then add the path to the file with the function in the TEMPLATE_CONTEXT_PROCESSORS tuple in your settings.py (ie: yourapp.contextprocessors.resource_urls).
from django.conf import settings
def resource_urls(request):
"""Passes global values to templates."""
return dict(
TIME_ZONE = settings.TIME_ZONE,
)
Now you can refer to these keys in your templates as expected: {{ TIME_ZONE }}.
I need to get an environment variable (ex: Mixpanel_Token) in all my templates, and without creating a new view in Django.
From what I read on SO, I should use a Template Context Processor.
The context_processor is defined in context_processors.py file:
from django.conf import settings
def settings_mixpanel(request):
ctx = {
"MIXPANEL_TOKEN": settings.MIXPANEL_TOKEN,
}
return ctx
In my settings.py file:
TEMPLATE_CONTEXT_PROCESSORS = (
'utils.context_processors.settings_mixpanel',
)
The issue I encounter is how to define MIXPANEL_TOKEN as a context variable in all my templates, given that all my views are already created in Django.
I don't want to recreate a view like the below one, using render_to_response function:
def index(request):
return render_to_response("index.html", {},context_instance=RequestContext(request))
You don't need to do anything special. As long as your template is rendered with RequestContext, you'll be able to access your variable with {{ MIXPANEL_TOKEN }}.
It is quite easy and straightforward: the context processors are called by RequestContext(...). If you do not use RequestContext(...), the context processors will not be used and will therefore not be of any value. You do not necessarily need to use render_to_response, but RequestContext is a must. Like it or not, that is how Django works. But from my personal view, changing your existing views to use RequestContext is not really a big thing, is it?
since Django 1.8 registring of custom context processor for templates happens via: TEMPLATES-> OPTIONS -> context_processors see here for reference: https://docs.djangoproject.com/en/1.10/ref/templates/upgrading/#the-templates-settings
In my view, if I specify
def myView(request):
return render_to_response('myTemplate.html', {'user': request.user,},
context_instance=RequestContext(request))
then I can access settings such as STATIC_URL in myTemplate.html.
However, if I specify
def myView(request):
return render_to_response('myTemplate.html', {'user': request.user,})
then I cannot access STATIC_URL. In this latter case, {{ STATIC_URL }} just yields an empty string in the rendered page. In the former case, {{ STATIC_URL }} yields the proper string for the static URL ("/static/").
Why do I need to send a request context to access the STATIC_URL setting in my template?
I am running Django 1.4 on Apache 2.
Read the docs for a better answer. But there is the short answer:
This is because of DRY (DonĀ“t Repeat Yourself), think this: what if you need set the same variable in all the templates through all the views?: context_processors, are methods that add variables to your templates in a more ordered way.
I quote:
Django comes with a special Context class, django.template.RequestContext, that acts slightly differently than the normal django.template.Context. The first difference is that it takes an HttpRequest as its first argument. For example:
c = RequestContext(request, {
'foo': 'bar',
})
The second difference is that it automatically populates the context with a few variables, according to your TEMPLATE_CONTEXT_PROCESSORS setting.
To access the STATIC_URL setting you need to send a request context because by default the RequestContext instance is automatically populated with some variable, accordingly with the TEMPLATE_CONTEXT_PROCESSORS settings which, by default too, reads this:
(...
"django.core.context_processors.static",
...)
About the django.core.context_processors.static context processor, the docs states:
If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every
RequestContext will contain a variable STATIC_URL, providing the value
of the STATIC_URL setting.
If instead, you don't specify the context_instance=RequestContext(request) part. Consider this signature:
render_to_response(template_name[, dictionary][, context_instance][, mimetype])
In this case a basic Context instance is used and (for this reason) only the given dictionary items get injected into the template. This dictionary could or couldn't contain the value of settings.STATIC_URL.
Note: as pointed out in another answer, since Django 1.3 you can directly use the render shortcut instead of render_to_response() with a context_instance argument.
References to official documentation:
render_to_response
Subclassing Context: RequestContext
django.core.context_processors.static
render shortcut
Since you're on 1.4, use the newer render() shortcut. Then you can do:
def myView(request):
return render(request, 'myTemplate.html', {'user': request.user,})
my question is:
Should I use Template context processor for global variable like category list ?
I have globs.py
from news.models import Category
def globs(request):
cats = Category.objects.all()
return {'cats': cats}
and in settings.py
TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"globs.globs",)
And when I use in template 'cats' it works fine on developer server.
On my hosting I have a problem:
Error importing request processor module globs: "No module named globs"
Can I use something else for global variables?
globs.py needs to be in your importable path on your hosting server. You could move it to your news directory and use "news.globs.globs" in TEMPLATE_CONTEXT_PROCESSORS.