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).
Related
I've formatted my base page properly and I have used the correct tags in my HTML pages, yet my local css file (main.css) will not load.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/main.css' %}"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#300&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% block script %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/07a07b3c8d.js" crossorigin="anonymous"></script>
{% endblock %}
<title>{% block title %}Edward's Portfolio{% endblock %}</title>
<style>
body {
font-family: "Source Code Pro", monospace;
}
</style>
{% endblock %}
</head>
<body>
{% block content %}
<h1>My Portfolio</h1>
{% endblock %}
</body>
</html>
Settings.py:
from pathlib import Path
import os.path
# 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.2/howto/deployment/checklist/
# 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',
'PortfolioApp'
]
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 = 'Portfolio.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',
'django.template.context_processors.media'
],
},
},
]
WSGI_APPLICATION = 'Portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.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/'
STATIC_ROOT = [os.path.join(BASE_DIR, 'static')]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"
Here is the structure of my static folder:
I have set my STATIC_ROOT and STATIC_URL correctly in settings.py but I have still found no success. If I could get some assistance I would appreciate it.
If your trying to do this with DEBUG=True you also need to set STATICFILES_DIR
https://docs.djangoproject.com/en/3.2/howto/static-files/#configuring-static-files
If you can post your settings.py with ALL of these set wecan help.
STATIC_ROOT is used in production, with DEBUG to False and you run
python manage.py collectstatic. So if your in production and having this issue you first need to set the urls for django to serve static files
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
then run the command python manage.py collectstatic
A quick example for specifying static directory in production/dev (DEBUG=True/False)
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = BASE_DIR / 'static' # this is a top-level static directory (same level as manage.py), you can create a list of dirs if you have static files in each app. This value is checked DEBUG=True
else:
STATIC_ROOT = BASE_DIR / 'static' # this value is checked in production
Update your static settings like this:
STATIC_URL = '/static/'
STATIC_ROOT = f'{BASE_DIR}{STATIC_URL}'
STATICFILES_URL = '/staticfiles/'
STATICFILES_DIRS = [f'{BASE_DIR}{STATICFILES_URL}',]
And inside urls.py, write this:
from django.conf import settings
from django.conf.urls.static import static
# After urlpatterns
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then rename your static folder to staticfiles
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.
I am getting the following error after I added href="{% url 'cart-add' product.id %}" to the add to cart button on my product.html file:
NoReverseMatch at /3/
Reverse for 'cart-add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$']
I believe that it's a urls pathing problem or settings, but I'm not sure how to resolve it. In case there are relevant files I missed displaying here, here is my github: https://github.com/sebapaik/django-shop
My product.html file looks like this:
{% extends "shop/base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-4">
<img class="img-thumbnail" src="{{ object.imageurl }}" alt="">
</div>
<div class="col-lg-8">
<h2>{{ object.brand }} {{ object.pname }}</h2>
<p>${{ object.price }}</p>
<p>{{ object.description }}</p>
**likely the problem below**
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' product.id %}">Add to cart</button>
</div>
</div>
{% endblock content %}
My Project/urls.py (main) looks like this:
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('admin/', admin.site.urls),
path('', include('shop.urls')),
path('cart/', include('cart.urls')),
]
My shop/urls.py looks like this:
from django.urls import path
from .views import ProductListView, ProductDetailView
from . import views
urlpatterns = [
path('', ProductListView.as_view(), name = 'shop-index'),
path('<int:pk>/', ProductDetailView.as_view(), name = 'shop-product'),
]
My cart/urls.py looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='cart-add'),
path('', views.cart_detail, name='cart-detail'),
]
My settings.py looks like this:
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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#9k!nb!1wi5*d=+*#3j+$gl%(#$z(c1aqsyh1p+qqs#)yeuh*_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'cart.apps.CartConfig',
'crispy_forms',
'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 = 'Project.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 = 'Project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.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/2.1/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.1/howto/static-files/
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
I am using Django 2.1.1, Python 3.6, and Windows 10
Your product.id is empty according to the error message. You should use object.id instead in your template:
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' object.id %}">Add to cart</button>
It seems that Django recognise your request url is '/3/', what you want to reverse is 'car/add/3/', you could try simply use [href="/cart-add/{{product.id}}'"] to replace [href="{% url 'cart-add' product.id %}"].By the way, while your 'shop/urls.py' and 'cart/urls.py' has the same line "path('add//', views.add_cart, name='cart-add'),"? It may lead to some other problems.
Code snippet managed static files in settings.py as follows.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(
os.path.dirname(__file__),
'static',
),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/'
],
'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',
],
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
],
'debug' : True
},
},
]
STATIC_URL = '/static/'
url.pyfile is as follows.
from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
admin.autodiscover()
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/$', Profile.as_view()),
]
views.pyfile is as follows
{% load staticfiles %}
<html>
<head>
<title>Django</title>
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" media="screen">
</head>
<body>
{% block content %}
<h1 class="text-info">Hello {{name}}!</h1>
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
When I run server, browser can't find bootstrap.min.js file.
Page not found at /static/bootstrap/css/bootstrap.min.css
http://localhost:8000/static/bootstrap/css/bootstrap.min.css
'bootstrap/css/bootstrap.min.css' could not be found
It seems that the static files url is correct.
But browser can't find the static files.
Please tell me the reason and how can I handle it?
To serve the static files during development you should add to your urls.py the following code:
from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/$', Profile.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And you should create the path in your project folder static/your_app/your_files
I'm trying to send input text from index.html to my view function that is "result".
When I click the 'Generate Summary' button its shows csrf verification failed.Csrf token missing.Urgent help required.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Input
from django.views.decorators.csrf import csrf_protect
def home(request):
input=Input.objects.all()
template=loader.get_template('home/index.html')
context={
'input':input,
}
return HttpResponse(template.render(context,request))
def result(request,input_text):
Input.input_text = request.POST('input_text')
return HttpResponse("<h1> text is"+Input.input_text)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
{% load staticfiles %}
<link rel='stylesheet'href="{% static 'css/bootstrap.min.css' %}" type='text/css'/>
</head>
<body background="/static/home/img/bg.jpg">
<center><h1> <font color="white" >Summarizeit.com !</h1></center>
<form name="myform" action="." method="post">{% csrf_token %}
<div class="form-group">
<center><label for="abc">Input Text</label>
<input type="text" name="input_text"class="form-group" id="abc"placeholder="Text input">
</div>
<br><br>
<center><button type="submit" class="btn btn-default"> Generate Summary !</button>
</form>
</body>
</html>
home/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
]
finalproject/urls.py(Root Project)
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('home.urls'))
]
models.py
from django.db import models
class Input(models.Model):
input_text = models.CharField(max_length=250)
def __str__(self):
return self.input_text
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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y)m04wnmm%i_#uih%^j5&aqeozlp!gt#px&z!*uf=-%v98x#-i'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'home',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'finalproject.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 = 'finalproject.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
For some reason you're rendering your template the hard way, which bypasses all the automatic things that Django does for you: most importantly, running context processors that include the CSRF token.
Your view should be this:
def home(request):
input=Input.objects.all()
context={
'input':input,
}
return render(request, 'home/index.html', context)
Note also that your setting of Input.input_text in the result view makes no sense at all; you need to create an instance of Input, set its input_text, then save it.