I'm using flatpages to add my content.
I was wondering if there was a way to get the active page so I can style it properly on my navigational bar?
Thanks!
The flatpages app uses RequestContext, which means that details from the request are pushed up through the middleware. You can access these request variables in templates if the request template context processor is enabled. Once you enable this, then all your templates will have access to the request, and from there you can get the current requested URL.
So,
Enable the django.core.context_processors.request template context processor (its not enabled by default). You need to make sure you don't disable the default context processors, so add this to your settings.py:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
In your template, use {{ request.get_full_path }} or {{ request.path }} depending on what you need.
If your using django flat pages, then you will already have the URL's defined.
EG: url(r'^license/$', 'flatpage', {'url': '/license/'}, name='license'),
Using request.path_info should get you the current page. Is that what you where looking for is there of is it something else ?
<a href="{{ flatpage.url }}" {% if flatpage.url == request.path %}class="active-page"{% endif %}>{{ flatpage.title }}</a>
If you have issues with your request context, you can check Burhan Khalid's answer.
Related
I am using django's template engine to render my email templates.
I have no RequestContext when rendering my email, there for I have no access to my STATIC_URL and cant use the {% url %} template tag.
How can I make it work while I am not generating the email from a view function ?
if you want to add domain/url you may get it from Site model:
message_data.update({'site': Site.objects.get_current()})
I have no idea why you think you need RequestContext for the {% url %} tag. It's a normal tag, you can use it in any template.
And STATIC_URL is just a setting: if you can't get it from the context processor, just pass it in manually into the template context: context['STATIC_URL'] = settings.STATIC_URL, or even use the {% static %} template tag.
How can i get the current user in a django template tags? (request object is not accessible)
Or how can i access to request object?
If you want to access the current user in a template tag, you must pass it as a parameter in the templates, like so:
{% my_template_tag user %}
Then make sure your template tag accepts this extra parameter. Check out the documentation on this topic. You should also check out simple tags.
The user is always attached to the request, in your templates you can do the following:
{% if user.is_authenticated %}
{% endif %}
You don't have to specify "request" to access its content
UPDATE:
Be aware: is_authenticated() always return True for logged user (User objects), but returns False for AnonymousUser (guest users). Read here: https://docs.djangoproject.com/en/1.7/ref/contrib/auth/
This question was already answered here:
{% if user.is_authenticated %}
<p> Welcome '{{ user.username }}'</p>
{% else %}
Login
{% endif %}
and make sure you have the request template context processor installed in your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)
Note:
Use request.user.get_username() in views & user.get_username in
templates. Preferred over referring username attribute directly.
Source
This template context variable is available if a RequestContext is used.
django.contrib.auth.context_processors.auth is enabled by default & contains the variable user
You do NOT need to enable django.core.context_processors.request template context processor.
Source : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
Suppose you have a profile page of every registered user, and you only want to show the edit link to the owner of the profile page (i.e., if the current user is accessing his/her profile page, the user can see the edit button, but the user can't see the edit button on other user's profile page.
In your html file:
<h2>Profile of {{ object.username }}</h2>
{% if object.username == user.username %}
Edit
{% endif %}
Then your urls.py file should contain:
from django.urls import path
from .views import ProfileUpdateView
urlpatterns = [
...
path('<int:pk>/profile/update', ProfileUpdateView.as_view(), name = 'profile_update'),
...
]
considering you have appropriate ProfileUpdateView and appropriate model
I have this path in my urls.py:
archive_index_dict = {
'queryset': News.objects.filter(show=True),
'date_field': 'date',
'template_object_name': 'object_list',
}
...
url(r'^$', 'django.views.generic.date_based.archive_index',
archive_index_dict, name='news_archive_index'
),
Now I want to detect in template if a page is current (this is for menu styling). Neither {{ request.path }} nor {{ request.get_full_path }} work in template.
What should I use instead?
SOLUTION
To get request available in templates I had to add django.core.context_processors.request to TEMPLATE_CONTEXT_PROCESSORS. This is not set by default (since django 1.3).
Do you have 'django.core.context_processors.request' context processor set up? Almost all CBV use RequestContext by default
I have project in Django 1.3. In order to show username in all pages I use such tags in base.html
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}.
loggout</p>
{% else %}
loggin
{% endif %}
But if I dont return context_instance=RequestContext(request) from view value of user in template is empty. The 'django.contrib.auth.context_processors.auth' is included to TEMPLATE_CONTEXT_PROCESSORS.
Is it possible automaticaly include user to all templates?
since django 1.3. use shortcuts.render function and dont warry about requestcontext including to your views
You've given the answer yourself. As long as you use a RequestContext, it will be included in all templates.
If you really find that too much work, you could use the (new in 1.3) TemplateResponse class.
Or simply create a context processor. See
http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors
Put this in context_processor.py
def root_categories(request):
return {
'user': request.user,
}
in settings.py add the context processor.
now in your template try: {{ user }}
I am writing small social application. One of the features is to write user name in the header of the site. So for example if I am logged in and my name is Oleg (username), then I should see:
Hello, Oleg | Click to edit profile
Otherwise I should see something like:
Hello Please sign-up or join
What I want is to show this on every page of my site. The obvious solution is to pass request.user object into every view of my site. But here http://www.willmer.com/kb/category/django/
I read that I can simply access request object from any template, just by enabling:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
Not sure why but it actually didn't work :(
Maybe someone can help me and suggest a solution?
Thanks a lot,
Oleg
Also note that you should use django.core.context_processors.auth instead of django.core.context_processors.request if you don't need the whole request context. Then you can simply type:
Hello {{ user.get_full_name }}
in your template.
Don't forget to pass context_instance=RequestContext(request) when you call render_to_response (or use direct_to_template).
There are probably two issues here.
Firstly, if you redefine TEMPLATE_CONTEXT_PROCESSORS as you have done you will override the default, which is probably not a good idea. By default, the setting already includes the auth processor, which gives you a user variable anyway. If you definitely need the request as well you should do this (notice the +=):
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
Secondly, as described in the documentation here when using context processors you need to ensure that you are using a RequestContext in your template. If you're using render_to_response you should do it like this:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Use
from django.template import RequestContext
instead of
from django.template import Context
So now just call RequestContext(request, context)
More here.
Once you have set up the context process, the request is passed to the template as a variable named request. To access the user object within the variable you need to drill into it:
{{ request.user }}
Here is a list of attributes stored in the Django Request object. More specifically, here is the user attribute.
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
Would be enough if you have TEMPLATE_CONTEXT_PROCESSORS already set.
I think just by adding locals() can solve the problem.
return render_to_response('my_template.html',
my_data_dictionary,locals())