I can't get the user in django templates - python

I already saw all the links on stackoverflow related to this.
I am using Django 1.9.7 an I try to see in template if theuser is authenticated but I can't get the user.
Template code which is not printing anything:
{{ user.is_authenticate }}
{{ request.user.is_authenticate }}
Settings code:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
],
},
},
]
I already tried withou social.apps and still not working, any ideas?

Make sure you pass the request context in the view, it's what adds the user to the context...
from django.template import RequestContext
def some_view(request):
form = None
# request.user accesses user here
return render_to_response('some_template.html', {'form':form}, context_instance=RequestContext(request))
Now in the template you can use:
{% if request.user.is_authenticated %}{{ request.user.email }}{% endif %}

Related

why does the child template get overriden by the templates in extends when using the django framework

for login.html this is what I have
{% extends "./base.html" %}
{% block content %}
<h2>Tryin to Log In</h2>
{% endblock content %}
for base.html this is what I have
{% block content %}
<h2>base template</h2>
{% endblock %}
My problem is that the base.html overwrites the templates in login.html
I have looked into the settings.py and this is what I have
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
The Answer is That include inserts a template into the current one, and extend will declare the template given as an argument as the current template's parent

I was trying to add templates to my Django project but it returns an error: TemplateDoesNotExist at /

I get a mistake when tying to add templates to my Django project.
settings.py :
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
views.py:
def index(request):
a = models.User.objects.get()
return render(request, "main/list.html", {"list": a})
and list.html:
{% extends "base.html" %}
{% block title %}Chats{% endblock %}
{% block content %}
{% if list%}
{% for i in list%}
<h2>{{i.usrname}}</h2>
{% endif %}
The project folder itself looks like this:
Main folder is app.
Thanks for your help!
You should include the os.path.join(...) in the Template 'DIRS'
Example:
In settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Then in your folder structure, you should have
app_name (main app folder) --> templates --> app_name(again) --> templates go here.
EDIT: I forgot to mention that in order to do this you must import os
treid change TEMPLATE_DIRS completly with this
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

No module named 'django.core.context_processors' django template

i tried to make a template tag to get the logged in user request.user , i tried this
in the settings.py
'context_processors': [
'django.core.context_processors.request',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
and this is my template tag
from django import template
register = template.Library()
#register.simple_tag
def is_member(context):
request = context['request'].user
if request.user in request.user.model_name.admins.all:
return True
else:
return False
i have to make sure if the logged in user is one of members in admins (M2M) field
but i get this error
No module named 'django.core.context_processors'
and while i try to remove this line 'django.core.context_processors.request' in the settings.py file i get this error
'is_member' did not receive value(s) for the argument(s): 'context'
Updated - template
{% load my_tags %}
{% if is_member %}
<a class="nav-link" href="{% url 'listings:new_post' %}">
<i class="fas fa-user-plus"></i>create new post </a>
{% else %}
<a class="nav-link" href="{% url 'login'%}
<i class="fas fa-user-plus"></i>Login</a>
{% endif %}
any recommendation i will appreciate
thanks , art
Django documentation says:
django.core.context_processors
Built-in template context processors have been moved to django.template.context_processors
Now your template option should look like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Also to use context in simple tags add takes_context=True
#register.simple_tag(takes_context=True, format_string)
def is_member(context):
....
And in your template:
{% is_member as user_is_member %}
{% if user_is_member %}
...
{% else %}
...
{% endif %}

Django context processor doesn't display new context values in template

EDIT: Updated now that I've narrowed down the problem to the context processor variable not being available to a template that I'm loading with a custom tag.
I'm using Django 1.11 and this is my first time trying to use a custom context processor.
The problem is that the context variable I'm supposed to be adding from the context processor does not return anything from within a template loaded from a custom tag. I don't receive any errors.
So below {{ testcontext }} should return "IT WORKED!" and does so in my base.html template, but returns nothing in the template loaded with #register.inclusion_tag().
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'appname.context_processors.test_context',
],
},
},
]
context_processors.py:
def test_context(request):
return {'testcontext': 'TEST WORKED!'}
tags.py
from django import template
from appname.models import Category
register = template.Library()
#register.inclusion_tag('template.html')
def load_category(selected_slug=None):
return {
'categories': Category.objects.all(),
'selected':selected_slug,
}
views.py:
from django.views.generic import ListView
from appname.models import MyModel
class MyView(ListView):
model = MyModel
urls.py
from django.conf.urls import url
from appname.views import MyView
urlpatterns = [
url(r'^$', MyView.as_view(), name="home"),
]
template.html
{{ testcontext }}
So the problem was in my custom tag not carrying over the context when loading template.html. So the below code fixes it and my variable from the context processor is now working as expected.
tags.py
from django import template
from appname.models import Category
register = template.Library()
#register.inclusion_tag('template.html', takes_context=True)
def load_category(context,selected_slug=None):
return {
'categories': Category.objects.all(),
'selected': selected_slug,
'testcontext': context['testcontext']
}

Django 1.8 not using Jinja2 template engine

I have followed the instructions on using jinja2 with django1.8. --->
#settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
normpath(join(DJANGO_ROOT, 'templates/jinja2')),
],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'kuyuweb_dj_1_8.jinja2.environment',
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
],
},
},
]
I have a .py file including environment -->
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
and in my application folder i have templates/jinja2 folder.
I have created a simple view as:
def home(request):
works = Work.objects.filter(publish=True).order_by('-created_at')[:8]
return render(request, 'jinja2/home.html', {'works':works })
But for example when i try to use jinja2 template tag as {{ loop.index }} it does not work. {{ forloop.counter }} is still working.
Is there something that i miss?
The jinja templates for your app should be in yourapp/jinja2, not yourapp/templates/jinja2.
If the template is at yourapp/jinja2/home.html, then your render line should be
return render(request, 'home.html', {'works':works })

Categories

Resources