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

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']
}

Related

TemplateDoesNotExist at / template path

I want to create the backend of a portfolio and I'm trying to use a template but it says it doesn't exist but shows the correct file path in the error message.
This is the urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is my views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
def home(request):
template = loader.get_template('home.html')
return HttpResponse(template.render(request))
And this is my templates setting:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
....
],
},
},
]
The directory structure is:
Core is the app name
Give this a try
change the home view to
def home(request):
return render("home.html")
and sett DIRS to blank in settings.py
TEMPLATES = [
{
...
'DIRS': [],
...
}
]
i would suggest you try this in your settings.py
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / 'templates'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR,],
'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',
],
},
},
]
and after that request you html in your views.py
def home(request):
return render(request, 'home.html')
and in you urls.py
path('',views.home, name='home')
this better and much cleaner way to tell django where to look fot templates and tell me if you still geting error
I fixed it by moving the statics and template directories into the app directory.

Django Model Forms ( Template Doesn't Exist)

I'm working on Django model forms. I have created forms.py and added the following:
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price'
]
And I have rendered this out in my views.py as it follows:
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, "products/product_create.html", context)
and I have added urls.py:
from django.contrib import admin
from django.urls import path
from pages.views import home_view , contact_view, about_view, social_view
from products.views import product_detail_view, product_create_view
urlpatterns = [
path('', home_view, name='home'),
path('contact/', contact_view),
path('admin/', admin.site.urls),
path('about/', about_view),
path('create/', product_create_view),
path('product/', product_detail_view),
path('social/', social_view),
]
I have migrated everything and saved all files, but when I want to go to my create URL, I get this error:
TemplateDoesNotExist at /create/
products/product_create.html
Request Method: GET
Request URL: http://127.0.0.1:8000/create/
Django Version: 3.2.4
Exception Type: TemplateDoesNotExist
Exception Value:
products/product_create.html
Exception Location: C:\Users\Invoker\dev\trydjango\env\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable: C:\Users\Invoker\dev\trydjango\env\Scripts\python.exe
Python Version: 3.9.5
Python Path:
['C:\\Users\\Invoker\\dev\\trydjango\\src\\sadra',
'C:\\Program Files\\Python39\\python39.zip',
'C:\\Program Files\\Python39\\DLLs',
'C:\\Program Files\\Python39\\lib',
'C:\\Program Files\\Python39',
'C:\\Users\\Invoker\\dev\\trydjango\\env',
'C:\\Users\\Invoker\\dev\\trydjango\\env\\lib\\site-packages']
Server time: Wed, 23 Jun 2021 08:20:29 +0000
I have created a template as well:
{% extends 'base.html' %}
{% block content %}
<form>
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
{% endblock %}
Templates in settings.py would be like this:
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',
],
},
},
]
I have my templates in a folder called templates in the root directory. In there I have another folder called products which includes detail.html and product_create.html
What should I do?
I'm a little unclear as to your dir structure as you say "another directory", not a sub directory.
Good practice in Django is to nest dirs under a templates dir using the appname, so in our case
project/templates/products/product_create.html
Should do the trick.
You can have the templates folder in the project root, or you can have it in an app dir for dev (since you have set APP_DIRS to True), but you need to keep the same nesting structure.
As it stands, your project is simply not finding the correct template. Your view has the right path, but the template is in the wrong place.

How to make Django use current application's templates folder?

Right now I have a Django project with three apps. In my last app, the index.html loaded by my views.py is the index.html in another app's templates folder. Note this is how it is actually loading it, but not how I intend it load. The index.html in templates where the corresponding views.py is defined is not used. What I am wondering is how I define my settings so that the templates folder for the current application directory is used. This is my settings.py with respect to templates:
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',
],
},
},
]
This is the call to index.html
def indexView(request):
form = FriendForm()
friends = Friend.objects.all()
return render(request, "index1.html", {"form": form, "friends": friends})
A good practice is that from the inside of your urls.py from your app, you add :
app_name = 'your_app_name' # Now, you can call this app from the {% url tag %}
And your template structure should contain app directories, and when you want to render to a different template you can use :
return render(request, 'myApp1/index.html')
return render(request, 'myApp2/index.html')
But remember, in your main templates folder, you need to add 2 directories,
templates/myApp1/index.html,
and
templates/myApp2/index.html
And finally, did you added app_name to your apps URLs? And after that try with the first one, or with the full path.
{% url 'myApp1:post_friend' %} or full path {% url 'myApp1/index.html' %}

return render method does not working in django

Hi I am very new to the Django and trying to learn going through the vidoes&docs but stuck return the html page from templates.
Though posts/index.html exists, getting the error "TemplateDoesNotExist at /posts/"
not sure where did I wrong, please advise.
here are my directory structure
djangoproject/urls.py
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^posts/', include('posts.urls')),
]
and Django app called "posts"
posts/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index')
]
posts/views
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'posts/index.html')
posts/templates/posts/index.html
<h3>message from index.html</h3>
here is my TEMPLATES from settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'posts/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',
],
},
},
]

I can't get the user in django templates

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 %}

Categories

Resources