I'm having trouble passing a variable from view to an html file. This is what I did so far:
My root directory (where the manage.py file is) contains the following folders:
myapp
myproject
templates
myproject/urls.py looks like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls'))
]
myproject/settings.py:
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',
],
},
},
]
myapp/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
templates/index.html:
<p>Hello {{ name }}</p>
When running the server locally, the only thing it shows is "Hello" without the name. What's wrong?
So let's start with views.py. When your urls.py calls your function in views.py, it's asking it to render a template.
Let's walk through a view function:
def index(request): the function the view
context = {'name':'Sol'} the key in the dictionary is what the HTML can call it and the value is what HTML gets back. So, when you do "{{ name }}" in HTML, it is replaced by Django with "Sol".
return render(request, "index.html", context) Making Django render it, request is the parameter from the function, "index.html" is the html file that Django is going to render, and context is the key + value pair that Django is going to use to replace.
Related
Please can you help me understand what I have done wrong here, I am sure it's a very simple problem but, I am new to django and especially the latest version...
I believe and as far to my research that I have routed my views to the best of my knowledge, please may you help identify my issue, I am getting an error:
"Page Not Found"
url.py from my app
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
views from my app
from django.shortcuts import render
from requests import request
# Create your views here.
def index(request):
return render(request, 'landing_page/index.html')
url from my project folder
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('/', include('comp.urls')),
path('admin/', admin.site.urls),
]
urls from my project
and then here is my project and template folders, I have attached an image for your ease of helping me:
In settings.py file, just add this:
os.path.join(BASE_DIR, 'templates')
EX:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #Removed landing_page from here
'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',
],
#Removed libraries from here
},
},
]
My index is loading well on browser, but when I click home page, there is nothing 404 error, is responding static/index.html, (when I click home page or any other such as contact, it is searching for html in static) why is it asking for index.html in static files and how can I rectify that?[
I stored my html files on templates folder thinking that when i clicked my dropdown, they were going to apper on my web.
if you create your index.html file on templates/index.html,then you can use this settings on your settings.py file:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Add 'TEMPLATE_DIR' here
'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 view you need to render that file:
def home(request):
return render(request, 'index.html', context=context)
You have to use a TemplateView. It is just a simple view that serve a template html.
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = "PATH_TO_INDEXHTML"
Just add an url in urls.py for serving this view and let's go
from django.urls import path
from .views import IndexView
urlpatterns = [
path('index', IndexView.as_view(),
]
More information about templateview: https://docs.djangoproject.com/fr/4.1/ref/class-based-views/base/#django.views.generic.base.TemplateView
Hi i'm just getting started with Django and i'm running a project, I have created an HTML file and this is the views.py
def index(request):
return render(request, "hello/index.html")
and this is the urls.py inside the maine file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include("hello.urls"))
]
and this is the urls.py inside the project file
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
and i got this error
view from my project
Make sure You have template folder same as where your manage.py
and also in settings.py
'DIRS': [os.path.join(BASE_DIR, 'templates')],
You have a typo. You have written templetes instead of templates
The problem is that you have simply misspelt the the template folder as templetes within your hello app. Rename it as templates and it will work
Add this to your main settings.py file.
and replace YOUR_APP_NAME with your django app name
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'YOUR_APP_NAME/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',
],
},
},
]
Try creating the folder named templates inside the hello app. Then create a folder named by the app name 'hello'. That will enable django to read inside that folder and fetch for the template named index.html.
And the path will look like
projectDir/hello/templates/hello/index.html
Do so, hope it will help.
I am new to Django. So I am trying to add a HTML template to the views.py but it is showing an error, it would be great if you would help me.
The full Error that I am seeing:
TemplateDoesNotExist at /
platform/home.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.0.8
Exception Type: TemplateDoesNotExist
Exception Value:
platform/home.html
Exception Location: C:\Users\Adeel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\Adeel\AppData\Local\Programs\Python\Python38-32\python.exe
Python Version: 3.8.3
Python Path:
['C:\\Users\\Adeel\\Google Drive\\Visual Studio\\Personal Portfolio\\Portfolio',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\Adeel\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Adeel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\Pythonwin']
Server time: Tue, 13 Oct 2020 06:14:44 +0000
views.py:
from django.shortcuts import render
def home(request):
return render(request, 'platform/home.html')
urls.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from Platform import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='Home'),
]
settings.py:
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',
],
},
},
]
My HTML template that i am trying to add:
<h1>This is my project</h1>
Add the template to your directories
TEMPLATES = [
{
...
'DIRS': [
os.path.join(BASE_DIR, 'your/way/to/templates'),
],
...
]
After that
def home(request):
return render(request, 'home.html')
Hope I didn't miss anything
EDIT
You should have a separate folder with templates
and in urls.py
from . import views
As the question implies, I am trying to set up my urls.py file to point towards my index.html file.
Here is the structure of my project:
-->mysiteX
---->.idea
---->mysite
------->migrations
__init__
admin.py
apps.py
models.py
test.py
views.py
---->mysiteX
-------->templates
index
---->css
---->fonts
---->js
---->vendors
__init__
settings
urls
wsgi
----->venv
db.sqlite3
manage
This is what my urls.py file looks like
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^index/', admin.site.urls),
]
my views.py file
from __future__ import unicode_literals
def index_file(request):
return render(request, "index.html")
settings.py:
import os, sys
abspath = lambda *p: os.path.abspath(os.path.join(*p))
PROJECT_ROOT = abspath(os.path.dirname(__file__))
sys.path.insert(0, PROJECT_ROOT)
TEMPLATE_DIRS = (
abspath(PROJECT_ROOT, 'templates'),
)
When I run manage.py I get this page
Update after making changes to my urls.py file to this extent:
from django.conf.urls import url
from django.contrib import admin
from gradientboost import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$',views.index_file,name='index')
]
This is what I am getting
Second Update
changed my settings.py file according to an answer given
import os, sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'mysiteX/templates')
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_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',
],
},
},
]
However still getting this error
You Need To Change Your Urls.py
Because You Are Changing Admin Url Admin Url Is For Admin Login And For Website Control!
and if you add index/ than you need to type in your brower like that domainname.com/index
So if you Want Your index.html show on website home page try my code:
Try This If You browsing this link 127.0.0.1:8000
from django.conf.urls import url
from django.contrib import admin
from mysite import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index_file, name='YOUR NAME')
]
And if you trying this link 127.0.0.1:8000/index Try This:
from django.conf.urls import url
from django.contrib import admin
from mysite import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/$', views.index_file, name='YOUR NAME')
]
Also Add This In Your Settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'mysiteX/templates')
And Also Add This In your Settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_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',
],
},
},
]
create a html template index.html and your url should be redirected the view.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', your_view, name = 'index'),
]
You don't reference templates from your urls.py. That is for matching routes up to view functions, and it is the view's job to tell Django to render a template, if appropriate. You already have a simple view that renders index.html, you just need to reference it in your urlconf.
If you want your index.html rendered at the root of your site, then you need to add this line to your urls.py (EDIT: fixed the route):
url(r'^$', index_file)
You will also need from mysite.views import index_file at the top of your urlconf.