I made a simple page to serve a static CSS in django but I always get a PAGE NOT FOUND error.
Views.py:
def login_user(request):
return render_to_response('new_file.html')
urls.py:
from django.conf.urls import patterns, include, url
from bookmarks.views import *
import os
from django.conf import settings
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
site_media=os.path.join(os.path.dirname(__file__),'site_media')
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'hello.views.home', name='home'),
#url(r'^hello/', include('hello.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#url(r'^admin/', include(admin.site.urls)),
(r'^$', main_page),
(r'^login/$', login_user),
(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT})
)
The template HTML:
<html>
<head>
<title>THIS IS MY PAGE</title>
</head>
<body>
<h1>NEW PAGE</h1>
<link href="/site_media/newstyle.css" rel="stylesheet" type="text/css" />
<p>{{ page_body }}</p>
</body>
</html>
The CSS:
#body {color:red;}
The settings.py site_media part:
MEDIA_ROOT = '/srv/www/hello/site_media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/site_media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = '/srv/www/hello/site_media/'
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/site_media/'
Try like this:
<link href="{{STATIC_URL}}css/newstyle.css" rel="stylesheet" type="text/css" />
Related
For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.
Here is my settings.py (showing you only main things)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('', include('main.urls')),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
Here is an example of using css files in my templates
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only#1.0.0/dist/bootstrap-grid.min.css">
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">
And this is the error in Chrome Console
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
And also i cant open css files in a new tab. I am getting that error
Also, if you remove %20 from the address bar, then I will open the css file
P.S.
I am trying to deploy it
1- Try to replace a slash forward path
<link rel="stylesheet" type="text/css" href=" {% static '/css/reset.css' %}">
2- whitenoise
pip install whitenoise
Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Here
# "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]
3- change your static URL like that:
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)
I think your mistake is that you put in a space in front of your static link
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
Try removing the space in front of {% so it will become
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
%20 is translated to a space character in URL's, so that why I think that's the issue
I am new to django. I wanted to upload an image but it doesn't show up on website. Instead, it shows a broken image icon. I tried to use load static block but it still doesn't work.
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Website</title>
</head>
<body>
<h1>Hello</h1>
{% load static %}
<img src="{% static 'webdev/static/webdev/images/images.jpg' %}">
</body>
urls.py file:
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
]
views.py file:
from django.shortcuts import render
from django.http import HttpResponse
def home_page(request, *args, **kwargs):
return render(request, 'home.html', {})
file tree: https://i.stack.imgur.com/EYxNI.png
The documentation on Serving static files during development explains how to set up static files. You need to add the views that serve the static files to the urlpatterns:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This will serve static files when DEBUG is set to True. In case of production (DEBUG = False), Django does not serve static files. Then you should configure the webserver (nginx/apache/…) to serve the static and media files, or work with a CDN.
Furthermore the path is:
<img src="{% static 'webdev/images/images.jpg' %}">
I dont know why image is not display on the home page. Please see my code. I am on windows running python3 and Django 2.1. Is there any setting need to be done in files somewhere in Django folders like any config file? Please guide
Settting File:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
URL file:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
import jobs.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home', jobs.views.home, name='home'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Model File
from django.db import models
# Create your models here.
class Job(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=300)
Home Page File
<html lang="en">
{% load static %}
<head>
And where I want to show the image is end of a div
<img src="{% static '9.jpg' %}" height="200"></img>
</div>
</section>
In settings.py you will need to add settings for MEDIA_ROOT and MEDIA_URL. That is what the ImageFile upload_to relates to. See the documentation here.
You can then for example reference the image in the home page template as follows:
<img src="{{ '/media/images/9.jpg' }}">
I am a bit confused on how to yield templates from other apps
Here is a picture of my project structure:
I am getting this error:
TemplateDoesNotExist at /
home.html
home/views.py:
class HomeView(generic.TemplateView):
template_name = "home.html"
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "home/static/home/js"),
os.path.join(BASE_DIR, "home/static/home/images"),
os.path.join(BASE_DIR, "home/static/home/css"),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
project/home/urls.py:
from django.conf.urls import patterns, url
from home.views import HomeView
urlpatterns = patterns('',
url(r'^$', HomeView.as_view(), name="home"),
)
project/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include("home.urls", namespace="home")),
)
project/templates/home/index.html
<!DOCTYPE html>
<html>
<head lang="en">
...
<!-- Fonts -->
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<!-- Custom CSS -->
<link href="{{ STATIC_URL }}boothie.css" rel="stylesheet">
<!-- Custom JS-->
<script src="{{ STATIC_URL }}boothie.js"></script>
<title>Boothie</title>
</head>
<body>
<div class="container">
...
</div>
</head>
{% block content %}{% endblock %}
</body>
</html>
project/home/templates/home/home.html:
{% extends index.html %}
{% block content %}
...
<script src="{{ STATIC_URL }}js/jquery.easing.1.3.js"></script>
<script src="{{ STATIC_URL }}js/boothie.js"></script>
{% endblock %}
Django stops at the first template that it finds matching the requested filename, and it will start at the templates directory in the app folder.
If it doesn't find it here, it will then go up the chain till it has searched all locations in the TEMPLATE_DIRS setting, and only then will it print an error that it cannot find a template. The way it searches for templates is defined by the TEMPLATE_LOADERS setting.
In your project layout, the template you want is located in the template directory of the home app, and inside this directory, under the home directory. Thus the template path should be home/home.html in your view:
class HomeView(generic.TemplateView):
template_name = "home/home.html"
If your templates directory is in your project's root you have to add it to setitngs.py
If it's the subdirectory of an app (that is in INSTALLED_APPS in settings.py) then the app template loader (enabled by default) will load it.
If your app is called home then you would have the templates dir inside the home dir, not home under templates which would make it accessible as home/home.html since it's under the home subfolder of the templates dir in settings.py
I have my css located in
static/css/boostrap.css
I currently have 2 views. A login view and a dashboard view.
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'logins.views.login', name='login'),
url(r'^dashboard', 'dashboards.views.dashboard', name='dashboard'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When i load up the login page it looks for the static files in
/static/css/login.css
But when i load the dashboard it looks for it in
dashboad/static/css/bootstrap.css
login.html css reference
<link href="static/css/signin.css" rel="stylesheet">
dashboard.html css reference
<link href="static/css/dashboard.css" rel="stylesheet">
Its adding part of the URL to the path off the static files and can not for the life of me figure out how to stop it.
settings.py
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
'/Users/chrismeek/Documents/Python/virtual/src/static/templates',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = '/Users/chrismeek/Documents/Python/virtual/src/static/static-only'
MEDIA_ROOT = '/Users/chrismeek/Documents/Python/virtual/src/static/media'
STATICFILES_DIRS = (
'/Users/chrismeek/Documents/Python/virtual/src/static/static',
)
You are using relative URLs to link to the assets: so they always start from the current page's directory.
Make sure you always use a leading slash:
<link href="/static/css/dashboard.css" rel="stylesheet">
Even better, use Django's static tag to automatically output the value of STATIC_URL, whatever it happens to be:
{% load static %}
...
<link href="{% static "css/dashboard.css" %}" rel="stylesheet">