it is displaying content in home.html. but it is not displaying the content(T1.name and T1.address) in index_detail.html after click on T1.name. Django version 4.0.6. The code is below please have a look into it. please solve the issue. Thank you for your time.
Settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-d4#4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'g6app',
]
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 = 'g6.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',
],
},
},
]
urls.py
from django.contrib import admin
from django.urls import path
from g6app.views import V1,V2
urlpatterns = [
path('admin/', admin.site.urls),
path("",V1.as_view(),name="v11"),
path("index/<int:pk>",V2.as_view(),name="index_detail"),
]
admin.py
from django.contrib import admin
from . models import T1
# Register your models here.
admin.site.register(T1)
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class T1(models.Model):
name=models.CharField(max_length=100)
address=models.TextField()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("index_detail",args=[self.pk])
views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import T1
# Create your views here.
class V1(ListView):
model=T1
context_object_name="con1"
template_name="home.html"
class V2(DetailView):
model=T1
context_object_name="con2"
template_name="index_detail.html"
home.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>home page</h1>
{% block context %}
{% for T1 in con1 %}
<h4>{{T1.name}}</h4>
<h4>{{T1.address}}</h4>
{% endfor %}
{% endblock context %}
</body>
</html>
index_detail.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>detail view page</h1>
{% block context %}
<h4>{{T1.name}}</h4>]
<h4>{{T1.address}}</h4>
{% endblock context %}
</body>
</html>
Try to write con2.name and con2.address. Because you are in the index_detail page an you mentioned con2 in view not a T1
The data is passed as object to the context, as as con2, so you render this with:
{% block context %}
<h4>{{ con2.name }}</h4>
<h4>{{ con2.address }}</h4>
{% endblock context %}
The variable name of home.html is thus not somehow reused: after rendering the template, the context is no longer available. If the user clicks on another link, then it will visit that view, and thus restart the rendering process with a new context.
Related
I am getting the error after adding the URL in the home.html file. I migrated before running the program. I used commands to migrate. i.e., python manage.py migrate. 2. python manage.py makemigrations app_name. Django version I am using is 4.0.6. Thank you
Settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-d4#4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'g6app',
]
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 = 'g6.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',
],
},
},
]
urls.py
from django.contrib import admin
from django.urls import path
from g6app.views import V1,V2
urlpatterns = [
path('admin/', admin.site.urls),
path("",V1.as_view(),name="v11"),
path("index/<int:pk>",V2.as_view(),name="index_detail1"),
]
admin.py
from django.contrib import admin
from . models import T1
# Register your models here.
admin.site.register(T1)
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class T1(models.Model):
name=models.CharField(max_length=100)
address=models.TextField()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("index_detail",kwargs={"pk": self.pk})
views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import T1
# Create your views here.
class V1(ListView):
model=T1
context_object_name="con1"
template_name="home.html"
class V2(DetailView):
model=T1
context_object_name="con2"
template_name="index_detail.html"
home.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>home page</h1>
{% block context %}
{% for T1 in con1 %}
<h4>{{T1.name}}</h4>
<h4>{{T1.address}}</h4>
{% endfor %}
{% endblock context %}
</body>
</html>
index_detail.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>detail view page</h1>
{% block context %}
{% for T1 in con2%}
<h4>{{T1.name}}</h4>]
<h4>{{T1.address}}</h4>
{% endfor %}
{% endblock context %}
</body>
</html>``
In your home.html you are trying to use this link:
<h4>{{T1.name}}</h4>
But in your urls.py you have:
path("index/<int:pk>",V2.as_view(),name="index_detail1"),
you need to change your path in urls.py to be same name as in your home.html.
path("index/<int:pk>",V2.as_view(),name="index_detail"),
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html.
I have the following structure
djangoAjax
settings.py
...
djangoAjaxApp
static
ok.css
templates
css_practice.html
My settings.py:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = '############################################'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"crispy_forms",
'djangoAjaxApp',
]
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 = 'djangoAjax.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 = 'djangoAjax.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), BASE_DIR / "static",
]
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
my html page:
<!DOCTYPE html>
{% load static %}
<html>
<head>
{% comment %} https://www.bing.com/videos/search?q=django+static+css&docid=608004894969656896&mid=E118E7C4ADFE161B3B12E118E7C4ADFE161B3B12&view=detail&FORM=VIRE {% endcomment %}
{% load static %}
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\static\ok.css' %}">
<title>Page Title</title>
</head>
<body>
<h1 class="ok">My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
views.py:
# css practice
def cssRender(request):
return render(request, "css_practice.html")
urls.py:
from django.urls import path
from .views import cssRender
urlpatterns = [
path('css/', cssRender, name='cssRender'),
]
I imagine I might be messing up the folder structure somehow... there is also a reference in the django docs: https://docs.djangoproject.com/en/3.2/howto/static-files/
about adding
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)
But since I am using, django.contrib.staticfiles in settings, I'm assuming this is done automatically.
Currently the page loads, but css is not applied.
Thanks for your help
settting.py:
STATIC_URL = '/static/'
Only one {% load static %} is enough in your html code:
<!DOCTYPE html>
{% load static %}
You have to Copy and Plast your STATIC files (Js, CSS, ...) in your templates.
It will look like that :
djangoAjaxApp
|_migrations
|_templates
| |_djangoAjaxApp
| |_css_practice.html
|_static
|___djangoAjaxApp (directory with the same App name)
|_(here all your static file)
Your HTML will look like this:
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">
views.py:
# css practice
def cssRender(request):
return render(request, "djangoAjaxApp/css_practice.html")
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.cssRender, name='cssRender'),
]
djangoAjax urls.py:
from django.conf import settings
from django.contrib import admin
from django.urls import path
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
Could you please try it.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
Just to remind you of it, have you tried hard refresh on your browser? I used to miss this when I was a beginner. (You can do it in chrome with ctrl+shift+r).
I'm making website using Python Framework of 'Django'.
I have some problems with Django about post number.
when I visit the website https://tutorialproject-ggurf.run.goorm.io/cafelist/1, I receive this message:
DoesNotExist at /cafelist/1
Cafe matching query does not exist.
settings.py contains:
"""
Django settings for tutorialdjango project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
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 = 'tutorialdjango.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 = 'tutorialdjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'MEDIA_ROOT')
MEDIA_URL = '/media/'
urls.py contains:
"""tutorialdjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from main.views import index, cafelist, cafedetails
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', index),
path('cafelist/', cafelist),
path('cafelist/<int:pk>', cafedetails, name='cafedetails'),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
views.py contains:
from django.shortcuts import render
from .models import Cafe
# Create your views here.
def index(request):
return render(request, 'main/index.html')
def cafelist(request):
cafelist = Cafe.objects.all()
return render(request, 'main/cafelist.html', {'cafelist': cafelist})
def cafedetails(request, pk):
cafeobj = Cafe.objects.get(pk = pk)
return render(request, 'main/cafedetails.html', {'cafeobj': cafeobj})
models.py contains:
from django.db import models
# Create your models here.
class Cafe(models.Model):
name = models.CharField(max_length = 50)
mainphoto = models.ImageField(blank = True, null = True)
content = models.TextField()
def __str__(self):
return self.name
index.html contains:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Django!</title>
</head>
<body>
<h1>Test!</h1>
{% load static %}
<img src="{% static 'jeju.jpg' %}">
</body>
</html>
cafelist.html contains:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>cafelist</title>
</head>
<body>
<h1>cafelist</h1>
<table>
{% for list in cafelist %}
<tr onclick="{% url 'cafedetails' list.id %}">
<td>{{ list.name }}</td>
<td>{{ list.content }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
cafedetails.html contains:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>cafelist</title>
</head>
<body>
<h1>cafelist</h1>
<p>
{{ cafeobj.name }}
</p>
<p>
{{ cafeobj.content }}
</p>
</body>
</html>
On your cafedetails page, you are getting this error message:
DoesNotExist at /cafelist/1 Cafe matching query does not exist.
This means that you haven't created a Cafe model with the pk of 1.
Try creating a few Cafe models from Django Admin or python manage.py shell and see if the error persists.
It seems that my static file doesn't work properly in my django project. I'm not sure whether this is exactly related to js files or the whole static file. Checking related questions, I couldn't find how to solve this problem. So, I send what my template should look like and how it looks in my browser in the below screenshots:
what my template should look:(when scrolling down, the background image also moves)
But this is how my browser shows the template: (no background images, no padding adjustments)
This is my base.html codes:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static 'css/all.css' %}">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- LightBox -->
<link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">
<title>BT Real Estate</title>
</head>
<body>
<!-- Top Bar -->
{% include 'partials/_topbar.html' %}
<!-- Navbar -->
{% include 'partials/_navbar.html' %}
<!--- Main Content -->
{% block content %} {% endblock %}
<!-- Footer -->
{% include 'partials/_footer.html' %}
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.bundle.min.js' %} "></script>
<script src="{% static 'js/lightbox.min.js' %} "></script>
<script src="{% static 'js/main.js' %} "></script>
</body>
</html>
Also, this is how I addressed my static file in settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'listings.apps.ListingsConfig',
'realtors.apps.RealtorsConfig',
'pages.apps.PagesConfig',
'django.contrib.auth',
'django.contrib.humanize',
'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 = 'btre.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'btre.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '******',
'USER': '******',
'PASSWORD': '******',
'HOST': 'localhost',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'btre/static')
]
# Media Folder Settings
MEDIA_ROOT = os.path.join (BASE_DIR, 'media')
MEDIA_URL ='/media/'
Here is my urls.py codes:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('pages.urls')),
path('listings/', include('listings.urls')),
path('admin/', admin.site.urls),
] + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Here is how I extend base.html in index.html: (I just brought the show case's codes here)
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<!-- Showcase -->
<section id="showcase">
<div class="container text-center">
<div class="home-search p-5">
<div class="overlay p-5">
<h1 class="display-4 mb-4">
Property Searching Just Got So Easy
</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit.Recusandae quad,
asperiores eveniet vel nostrum magnam
voluptatum tempore! Consectetur, id commodi!</p>
<div class="search">
<form action="search.html">
<!-- Form Row 1 -->
#pass
{% endblock %}
And finally, here is the hierarchy of my static file:
Why did such a problem happen? Can somebody help me out with this problem?
Thank you.
I think you have to include in your settings a media root and a media url. I use the following settings.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR),'static']
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
Also then in your URLS, make sure you have the following settings:
(first import static and settings), then enter the following code at the end!
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I think this might fix the problem if the images that aren't displaying are on your local machine.
Just remove the "/cover" and put just "fixed" instead of "fixed/cover" from the "main_app/static/css/style.css/showcase"
I am working on the login/logout functionality of a basic Django website. (CS50's Pinocchio's Pizza). The logout path is being injected into the URL & I am unsure as to why. My navbar links to the home page, yet when I click on it it redirects me to the logout page. Any other link I click, that link's path is added to the URL but attached to the logout path.
For example, clicking on the login button of my site, whose path is login_default, the url becomes:
http://127.0.0.1:8000/logoutlogin_default
Trying to click the link in the navbar that should link to the index page gets me:
http://127.0.0.1:8000/logout
The folder "orders" is an app which "pizza" is made aware of. All html pages are inside orders/templates/orders.
This is orders/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default", views.register_default, name = "register_default"),
path("register_setup", views.register_setup, name = "register"),
path("login_default", views.login_default, name = "login_default"),
path("login_setup", views.login_setup, name = "login"),
path("logout", views.logout_view, name="logout"),
]
In pizza/urls.py, the Orders app's URLs have been made known:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("register_default", include("orders.urls")),
path("register_setup", include("orders.urls")),
path("login_default", include("orders.urls")),
path("login_setup", include("orders.urls")),
path("logout", include("orders.urls")),
path("admin/", admin.site.urls),
]
This is orders/views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
# Create your views here.
def index(request):
# If user is not logged in
if not request.user.is_authenticated:
return render(request, "orders/index.html", {"message": None})
context = {
"user": request.user
}
return render(request, "orders/index.html", context)
def register_default(request):
return render(request, "orders/register.html")
def register_setup(request):
firstName = request.POST["userFirstName"]
lastName = request.POST["userLastName"]
email = request.POST["userEmail"]
pw = request.POST["userPW"]
user = User.objects.create_user(firstName, email, pw)
user.save()
return HttpResponseRedirect(reverse("index"))
def login_default(request):
return render(request, "orders/login.html")
def login_setup(request):
username = request.POST["loginName"]
password = request.POST["loginPW"]
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "orders/login.html", {"message": "Invalid Credentials"})
def logout_view(request):
logout(request)
return render(request, "orders/login.html", {"message": "Logged Out"})
This is base.html, which all other templates are based off of.
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}{% endblock %}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md bg-light">
Pinocchio's Pizza
<ul class="navbar-nav">
{% if message %}
<li class="nav-item">
Log Out
</li>
{% else %}
<li class="nav-item">
Log In
</li>
<li class="nav-item">
Sign Up
</li>
{% endif %}
</ul>
</nav>
{% block body %}{% endblock %}
</body>
</html>
This is login.html
{% extends "orders/base.html" %}
{% block title %}Log In{% endblock %}
{% block body %}
{% if message %}
<h1 class="text-danger">{{ message }}</h1>
{% endif %}
<div class="container-fluid">
<div class="row">
<div class="col-md-6 mx-auto mt-4">
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="loginName">First Name</label>
<input type="text" name="loginName" id="loginName" class="form-control">
</div>
<div class="form-group">
<label for="loginPW">Password</label>
<input type="password" class="form-control" name="loginPW" id="loginPW">
</div>
<button class="btn btn-success" type="submit">Log In</button>
</form>
</div>
</div>
</div>
{% endblock %}
This is pizza/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i0&iq&e9u9h6(4_7%pt2s9)f=c$kso=k$c$w#fi9215s=1q0^d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'orders.apps.OrdersConfig',
'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 = 'pizza.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 = 'pizza.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
Try changing pizza/urls.pyto the following:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("admin/", admin.site.urls),
]
the reason is the "" path should automatically include all the urls in orders.urls. Here is a link to the documentation: https://docs.djangoproject.com/en/2.2/topics/http/urls/#including-other-urlconfs
Another thing that I noticed that helps catch bugs is to include a / at the end of urls so in your orders/urls.py you can change it to the following.
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default/", views.register_default, name = "register_default"),
path("register_setup/", views.register_setup, name = "register"),
path("login_default/", views.login_default, name = "login_default"),
path("login_setup/", views.login_setup, name = "login"),
path("logout/", views.logout_view, name="logout"),
]