So i'm trying to build a basic blog in Django (am currently using the latest version of Django) and i'm running into a really annoying problem. When I try and set up my html templates, I keep on getting a templatedoesnotexisterror.
Here's the rub--if I set up my html templates in the root app of the project ("blogcode"), they run perfectly. But then, once I start running another app ("articles") and then I set up a templates folder using articles/templates/articles/homepage.html, all of the sudden, it doesn't work. I can't get django to look anywhere but in the root app directory to find and ultimately render templates.
In my settings.py file, i've the DIRS list set to 'templates'. When I tried changing it to os.path.join(BASE_DIR, 'templates') I get the same "templatedoesnot exist" error. Also, my app IS properly installed in the INSTALLED_APPS list in settings.
I've tried looking in other documentation, but the only hints I can find are really outdated. On the views.py, if I chop off the articles/, and just leave it as 'homepage.html' django renders it from the root app just fine and ignores the template in the articles app, but if I try and get it to render from the articles app, I get the "templatedoesnotexist" error. What's going on?
Here's my code:
articles/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.startpage, name='startpage'),
]
articles/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Article
def startpage(request):
return render(request, 'articles/homepage.html')
blogcode/settings.py
INSTALLED_APPS = [
'articles.apps.ArticlesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'horror_blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
WSGI_APPLICATION = 'horror_blog.wsgi.application'
Try register the app that way, and put django apps above your owns
Instead of
'articles.apps.ArticlesConfig',
Try this:
INSTALLED_APPS = [
''' django apps'''
'articles'
]
this 'DIRS': ['templates'] should be 'DIRS': [os.path.join(BASE_DIR, 'templates'),],
Related
I'm a beginner with Django and have been working a small project that requires quite a bit of styling. However, for some reason, Django isn't picking up on my static css file.
settings.py
from pathlib import Path
TEMPLATES_DIR = Path(BASE_DIR) / 'templates'
STATIC_DIR = Path(BASE_DIR) / 'static'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'CalculatorApp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Calculator.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'Calculator.wsgi.application'
...
STATIC_ROOT = Path(BASE_DIR) / 'static'
STATIC_URL = 'static/'
STATICFILE_DIRS = [
STATIC_DIR,
]
I double checked my spelling, settings.py directory, checked countless posts and can't seem to find a solution. This is my first time using stack overflow, so I'm assuming I just upload pictures of my code.
Edit: here are is my views.py and urls.py.
# Urls.py
from django.contrib import admin
from django.urls import path
from CalculatorApp import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
]
# Views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
I am a relatively inexperienced python/django programmer and have run into a issue that i am unable to resolve on my own, inspite of searching around for help. English is not my first language so please do not mind language related errors in my attempt to explain my problem.
My django 3.2 App uses stripe checkout for payment. While in development on my local machine, i could process payment and return to my apps success page, but after i deployed it to heroku, it processes the payment but wont return to my apps success page. I have installed the corsheaders package and have tried all the possible settings suggested here on stackoverflow and elsewhere. I am stating my settings below and also the stripe checkout views code. Any help will be highly appreciated.
all the relevant settings are as under
BASE_DIR = Path(__file__).resolve().parent.parent
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
'corsheaders',
'crispy_forms',
'sorl.thumbnail',
'cloudinary',
'storages',
# local
'accounts.apps.AccountsConfig',
'main.apps.MainConfig',
'api.apps.ApiConfig',
'cart.apps.CartConfig',
'payment.apps.PaymentConfig',
'order.apps.OrderConfig',
'setmenu.apps.SetmenuConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('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',
],
},
},
]
core.urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('api/v1/', include('api.urls')),
path('cart/', include('cart.urls', namespace='carturls')),
path('setmenu/', include('setmenu.urls', namespace='setmenu')),
path('orders/', include('order.urls', namespace='orders')),
path('payment/', include('payment.urls', namespace='payment')),
path('', include('main.urls', namespace='main')),
]
payment urls.py
app_name = 'payment'
urlpatterns = [
path('process/', login_required(views.payment_process), name='process'),
path('done/', views.payment_done, name='done'),
path('canceled/', views.payment_canceled, name='canceled'),
path('webhook/', views.webhook, name='webhook')
]
Payment apps view that processes payment
def payment_process(request):
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = int(order.get_total_amount() * 100)
session = stripe.checkout.Session.create(
line_items=[{
'price_data': {
'currency': 'inr',
'product_data': {
'name': f'Order number {order_id}',
},
'unit_amount': f'{total_cost}',
},
'quantity': 1,
}],
mode='payment',
success_url='https://myappname.herokuapp.com/payment/done',
cancel_url='https://myappname.herokuapp.com/payment/canceled',
)
return redirect(session.url, code=303)
even if i put a done/ it doesnt redirect. The below success urls work though and i am redirect to my home page and the admin page respectively.
success_url='https://myappname.herokuapp.com'
and
success_url='https://myappname.herokuapp.com/admin'
But ofcourse, ideally it has to return to the specific success page. The fact that it successfully redirects to https://myappname.herokuapp.com/admin, bothers me even more as to why it wont go to https://myappname.herokuapp.com/payment/done
I have tried to discard the payment urls and dump the payment routes in the core urls thinking that its not accessing custom namespaced urls, but that too did not work.
Please do point me to the right direction. I am inclined to think that my Cors settings are not right but then i have allowed all hosts and cors_origin_allow_all is true.The corsheaders middleware is also at the top as suggested but yet its not redirecting from stripe. So i feel like i have hit a wall.
Thanks a lot for your help
I have a serious problem with my Django application and is that I do not load the styles in my app, the error I get in console is as follows:
"It has been rejected to apply the style of 'http://127.0.0.1:8000/static/static/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled".
Failed to load resource: the server responded with a status of 404 (Not Found)
Settings.py:
from email.mime import application
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
import os
DEBUG = True
ALLOWED_HOSTS = ["*"]
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
MEDIA_URL = 'Imagenes/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Imagenes')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'clase',
'index',
'accounts',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djanpro.urls'
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',
],
},
},
]
...
this is urls.py file:
from xml.dom.minidom import Document
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from djanpro.settings import MEDIA_ROOT
urlpatterns = [
path('', include("index.urls")),
path('clase/', include("clase.urls")),
path("accounts/", include("accounts.urls")),
path('admin/', admin.site.urls)
]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
for now I can only view the html of my platform, however the images that are saved in the posts seem to be working.
I am developing a Django and using ImageFiled attributes into models that I need to display later. When I run the website in dev (DEBUG = True) it works, but when I change it to False (Production) uplaoded images do not display anymore and the console shows:
"GET HTTP/1.1" 200
As I saw in other open questionsI tried to add in settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
and in urls
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But this doesn't work and even creates the same issue as in production.
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home.apps.HomeConfig',
'gallery.apps.GalleryConfig',
'storages',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
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',
],
},
},
]
DEBUG = False
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_URL = 'static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
Update:
The documentation says:
URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments.
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES.
https://docs.djangoproject.com/en/1.8/ref/settings/#media-root----
I tried this and the problem is still there.
I normally set these in the urls.py for the project to handle media and static files correctly.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT).
I think you are missing the settings.DEBUG if statement in urls.py config.
The problem has been solved by using AWS storage instead of the server storage.
Effectively, as been said in the answers Django is not optimised to server static/media.
I made a new app for my webapp project using ./manage.py startapp webapplogin.
The templates all works however now I keep getting 'WSGIRequest' object has no attribute 'session' whenever I try to do anything with request such as logout(request) or login(request, user).
I don't understand what the issue is after about 6 hours of debugging/googling...
Do I need to go back to doing the webapp all in webapp instead of trying to split up the project into apps? The templating works fine as well as linking right now, just the no attribute 'session'...
project structure below
app_project
app_backend
settings.py
urls.py
wsgi.py
static
static_files
webapp
templates
webapp
base.html
home.html
admin.py
apps.py
models.py
tests.py
urls.py
views.py
webapplogin
templates
login
login.html
admin.py
apps.py
models.py
tests.py
urls.py
views.py
project settings below
INSTALLED_APPS = [
'webapplogin.apps.LoginConfig',
'webapp.apps.WebappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.humanize',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app_backend.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'app_backend.wsgi.application'
currently on 1.9, Django doesn't recognize the MIDDLEWARE setting. You should use the MIDDLEWARE_CLASSES setting
The reason this happens is because the order of the middleware is important.
During the request the Django session middleware must execute first in order to add the session object to the request.
Try the following :
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
]