Django Class-based View and URL configuration - python

I am trying to learn Django and I am stuck with Class-based views and URLconf. From what I understand I should see my test.html at localhost/app1/test1/test/test.html, but I get an error page not found. I am not sure what I am doing wrong.
#~/project_folder/mysite/ulrs.py
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/test1/', include("app1.urls")),
]
#~/project_folder/app1/urls.py
urlpatterns = [
path('test/', TemplateView.as_view(template_name="test.html"), name="home"),
]
#~/project_folder/static/templates
test.html
#~/project_folder/mysite/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'static/templates'),
],
'APP_DIRS': True,
...
}
STATIC_URL = os.path.join(BASE_DIR, 'static/')

Django html-templates are not supposed to be treated as static files and regular path for them is like "app/templates/app" (examine tutorial and demo-projects)
template file names are not exposed to the end-user and do not partake in url path, so
this particular setup
path('app1/test1/', include("app1.urls")),
path('test/', TemplateView.as_view(template_name="test.html"), name="home"),
actually means: for rendering response on url app1/test1/test/ request use test.html template. If you rename template filename to "whatever-foo-bar-my-template.html" url will not change.

Related

TypeError: render() missing 1 required positional argument: 'template_name'

I created simple form register user but something is wrong. This is my django project:
settings.py
account/urls.py
forms.py
views.py
Directories:
error:
I don't understand this issue. I use render(request, 'name_template', {}) but django request name_template. What did I do wrong?
Sorry for my english but I still learn ;)
in your path it should be
path('register/, views.register, ....)
Could you check your TEMPLATES section in settings.py. It looks something like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
},
]
Check if you have path specified to your templates in 'DIR' key.
If not, then add specified path to your templates folder.
TEMPLATES_DIR = os.path.join(BASE_DIR, 'account','templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIR': [TEMPLATES_DIR,]
},
]
Documentation
https://docs.djangoproject.com/en/4.0/ref/settings/#templates
you're mapped a wrong view inside urls.py
path('register/', views.render, name='register'),
Change it to
path('register/', views.register, name='register'),

How to resolve 'TemplateDoesNotExist' error when Django appears to be searching the correct path

I'm setting up the structure for a new project in Django. I've created the app 'accounts', within which I've added a templates folder containing an html template. However, when I go into the development server and click on a link to this page from my index page (which loads no problem), it returns a TemplateDoesNotExist error message.
I've examined the error message and the Template-loader postmortem details the correct pathway for my html template (I've checked this and made sure countless times), suggesting that Django is looking in the right place for it. However, it also says 'source does not exist'. Does anybody have any troubleshooting tips, considering Django appears to be searching the correct pathway?
# From settings.py ('accounts' is also included with INSTALLED_APPS):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# ...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# From urls.py:
from django.conf.urls import url, include
from accounts.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index, name="index"),
url(r'^accounts/', include('accounts.urls')),
]
# From urls.py (accounts):
from .views import signup
urlpatterns = [
url(r'^signup/$', signup, name="signup"),
]
# From views.py (accounts):
def signup(request):
return render(request, 'signup')
I guess do you have a newer version of django on your server machine.
DIRS is now (2.2) into TEMPLATES setting var. On django old version (ex: 1.8) was in DIRS setting var.
Then, check versions and move to newest one and use:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
on settings.

Why console is showing templates not defined error in django

I am new to django , I am facing one while django running server , I have copy and paste my code please tell me what is wrong with my code
'DIRS': [templates],
NameError: name 'templates' is not defined
in settings.py file , I have put templates in [] brackets
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',
],
},
},
]
this is my views.py
from django.http import HttpResponse
from django.shortcuts import render
def index(response):
return render(request,'index.html')
this is urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
templates should be string. so ['templates'] instead of [templates]
You need to change DIRS here
'DIRS': [os.path.join(BASE_DIR, 'templates')],
Here, Django expects it has a template path but you provide templates variable which does not have any path.
While others have already given right answers on how to fix it, but I would like to point out a minor thing that you are getting the NameError because you haven't defined the name templates.
The NameError is raised when the variable you are using is not defined anywhere in the program (if you defined it outside the current scope you will be getting UnboundLocalError).
If you define the name templates as a string for the absolute path to your template folder, this will work. Still, never use absolute path in your Django application cause it will become a headache while deployment.
You have to change your line to this
'DIRS': [os.path.join(BASE_DIR, 'templates')],
In the begging of the settings files you can see the BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Changing DIRS to
'DIRS': [os.path.join(BASE_DIR, 'templates')],
Will help the app to find the templates folder.
Just a personal advice in each app store the templates/appname folder for the specific app. It will help you to have a more robust Django app.
for example you have the polls app, inside the polls app it will be like this
pollsApp/templates/pollsApp/index.html etc.
Also here is the official guide, it might help you

TemplateDoesNotExist at /accounts/login/ error

I got an error:
TemplateDoesNotExist at /accounts/login/ registration/login.html.
I think I should create login.html file but probably it is not required in Django for default beahivor.
After I placed login.html in accounts/templates/accounts the error has not disappeared.What should I do next?
I wrote in urls.py of accounts,
from django.conf.urls import url
from django.contrib.auth.views import login, logout
urlpatterns = [
url(r'^login/$', login,
name='login'),
url(r'^logout/$', logout, name='logout')
]
in urls.py of parent app,
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^api/', include('UserToken.urls')),
]
in TEMPLATES of settings.py of parent app
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',
],
},
},
]
I found in blowser,
emplate-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/admin/templates/registration/login.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/templates/registration/login.html (Source does not exist)
I think maybe I should make templates folder.
Now,I made a directory like accounts/registration/accounts/login.html .
I cannot understand why error shows 2 ways directory to admin&auth.Should I make admin&auth directory?
For me worked adding:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
Take care to delete browser cache.
The pathnames in your error messages are showing a space character just after login/ - this is probably not contained in the actual filenames, thus the files can't be found. In one case it's a normal space, in the other it's a Unicode 'IDEOGRAPHIC SPACE' (U+3000). I don't see where this is coming from in your source code.
check all your folders name what you put same Error I also receiving.
I mistakenly put template instead of templates.
Django default takes templates folder rather than just template or any other name.
This resolves my problem.

Django 1.8 Cannot load the css template

I have CSS file at /ecomstore/static/css.css
I have already linked the css to the base.html within head tags by
<link rel="Stylesheet" type="text/css" href="/static/css.css" />
My urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from ecomstore import settings
from django.contrib.staticfiles import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^catalog/','preview.views.home'),
# url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
# { 'document_root' : '/home/yogesh/ecomstore/static' })
]
urlpatterns = [
# other commented code here
url(r'^catalog/?','preview.views.home'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root' : '/home/yogesh/ecomstore/static/' }),
]
Settings.py file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(CURRENT_PATH, 'templates')],
'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',
],
},
},
]
Static settings:
STATIC_URL = '/static/'
STATIC_ROOT = "/home/yogesh/ecomstore/static/"
Despite all this stuff i dont know why my css template is not loading. Also in the terminal i am getting the following indicating some sort of error.
[24/Nov/2015 11:11:36] "GET /static/css.css HTTP/1.1" 404 1735
Use {% static %} template tag:
{% load staticfiles %}
Configure static files dir in your settings and do not hardcode the path in your urlconf:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
)
Make sure you're serving static files during development:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Check that static file dir /home/yogesh/ecomstore/static/ is readable by your django process.
Static files
Store your files in /ecomstore/static/ecomstore/css.css instead of /ecomstore/static/css.css because Django look by default in all folders <app_name/static/<app_name>, then you don't have to had these folder in STATICFILES_DIRS variable.
Django documentation :
Store your static files in a folder called static in your app. For
example my_app/static/my_app/myimage.jpg.
Read this for more
information and configure your project : Managing static files
Templates
You did also a mistake in the configuration of your template. When you use os.path.json function, you don't have to have a / at the last folder. Just use os.path.join(BASE_DIR, 'templates')
Serving static file during development
Concerning serving static files, if you use the django built-in server, you don't have to configure anything, Django serve them by default. However, if you use gunicorn or uWSGI, yes you have to configure your project to serve static files.
You have to add this in your main <project_name>/<project_name>/urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now, your server will server static file based on STATIC_URL that you configured in your <project_name>/<project_name>/settings.py file.
Read this for more information : Serving static files during development

Categories

Resources