Why is Django template not responding to static files? - django

It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates.
Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution.
I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that.
Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday.
My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't want to work with 2/3 same css file and static folder if I can help it.
Here are some codes.
My folder structure-
Everytime I update the css and refresh the template my console is showing some kind of error, here they are-
Settings.py file seems correct. Here is the relevant part-
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
...
...
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
STATIC_ROOT= os.path.join(BASE_DIR, 'staticfiles')
my base.html -
{% load static %}
<!DOCTYPE html>
<html lang="en">
<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">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="{% static 'ok.css' %}"/>
</head>
<body>
{% block content %}
<h2 class="ok">This is a test</h2>
<div class="solved">This took a while!</div>
<div class="container">Didn't work on the other site!</div>
{% endblock content %}
</body>
</html>
and test.html -
{% extends "myapp/base.html" %}
{% block content %}
<h2 class="again">Content for My App</h2>
<p class="intro">Stuff etc etc.</p>
<p class="ok">write some more</p>
<div class="container">This should work</div>
{% endblock %}
URLs.py even though I think I am doing ok there -
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('base/', views.ok, name='base'),
path('test/', views.test, name='test')
]
And finally views.py , another page I don't think have any issues -
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {}
return render(request, 'myapp/index.html')
def ok(request):
return render(request, 'myapp/base.html')
def test(request):
return render(request, 'myapp/test.html')
If you can spot anything kindly let me know. Any help is appreciated. Thanks.

Related

Django static files not working in localhost

I have my Django app running on a development server. The HTML templates are serving fine but I'm really having a lot of trouble getting the static files to serve. I've tried lots of ideas from Stack Overflow but not getting anywhere.
I just get a 404 error on the image.
Can anyone help me please?
My urls.py is:
from django.contrib import admin
from django.urls import path
from app import views
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# The rest of my urls here...
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
my settings has included:
STATIC_ROOT = "/home/me/django-test/djangoproject/static"
STATIC_URL = 'static/'
and my template has:
<!doctype html>
{% load static %}
<img src="{% static 'e.png'%}">
It worked for me in django 3.2.
For local static you should create folder called "static" in your config folder
config it's folder created when you start project(may be you call it mysite or smth):
django-admin startproject config
create a "static" folder in the same folder where you have the file settings.py
#In settings.py:
STATIC_URL = '/static/'
# folder for static when you deploy your project on server(not for local develop)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# local (in config for runserver)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "config/static"),
]
Inside folder "static" place your css, js, img e.t.c folders
In our templates you have to do something like this:
<!DOCTYPE html>
{% load static %}
<html lang="ru">
<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">
<link rel="stylesheet" href="{% static 'css_custom/base_style.css' %}"/>
<title>{% block title %}TITLE{% endblock title %}</title>
</head>
Pay attention to my template tag
href="{% static 'css_custom/base_style.css' %}"
that means i load static from:
config/static/css_custom/base_style.css
Same thing for load image, in you template.html:
{% extends '_base.html' %}
{% load static %}
{% block content %}
<img src="{% static 'images/Bg.jpg' %}" alt="">
{% endblock content %}
that means static from:
config/static/images/Bg.jpg
or you can add relative path into your style.css for some classes like:
.header-home {
height: 40vh;
background-image: url("../images/Bg.jpg");
background-size: cover;
background-position: center;
text-align: center;
}
Hope it helps you

Static files doesn't load anymore - Django

In the beginning everything worked perfectly fine, but now I have a problem where my static files doesn't load. I think this is a very weird problem since I didn't really touch anything that could've had an influence on the problem when it happened. Everything else is working fine, I just can't get the static files for some reason. I sometimes get a 200 http response trying to get the static files like so:
[20/Aug/2020 16:12:51] "GET /order/checkout/ HTTP/1.1" 200 2029
[20/Aug/2020 16:12:51] "GET /static/my_pizza_place/js/client.js HTTP/1.1" 200 2194
[20/Aug/2020 16:12:51] "GET /static/css/master.css HTTP/1.1" 200 80
[20/Aug/2020 16:12:51] "GET /static/css/global.css HTTP/1.1" 200 530
But it's still not applying the styling to my html code. I usually just get a 304 http response on my client.js file though. I feel like I have tried almost everything at this point, so I hope you guys can help me figuring out what the problem is.
My files:
SETTINGS.PY
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
BASE.HTML
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
...
<link rel="stylesheet" href="{% static 'css/master.css' %}">
<link rel="stylesheet" href="{% static 'css/global.css' %}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="..." crossorigin="anonymous">
<script src="{% static 'my_pizza_place/js/client.js' %}" defer></script>
</head>
<body>
<div class="container mycontent">
{% block checkout %}
{% endblock %}
</div>
</body>
</html>
INDEX.HTML
{% extends 'base.html' %}
{% block content %}
...
{% endblock %}
URLS.PY - IN PROJECT FOLDER
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.HomePage.as_view(),name="home"),
path('customer/',include('customer.urls', namespace='customer')),
path('customer/',include('django.contrib.auth.urls')),
path('order/',include('orders.urls',namespace='order'))
]
VIEWS.PY
class HomePage(TemplateView):
template_name = 'index.html'
DIRECTORY STRUCTURE
Project
app_name
project_name
static
css
global.css
master.css
my_pizza_place
js
client.js
templates
base.html
If you need any more information please just ask. Thanks in advance
Your problem is simply that you should add {% load static %} in each file. You don't have to necessarily link the css files in each .html file, but in each file you should load the static files. I have faced this problem before and I am sure this will solve it for you, be sure to add the {% load static %} before the {%block content %} tag. If you need further explanation, comment below.

Can't figure out what did I miss here, it says 'list' is not a valid function. Any help would be appreciated

The error that occurs during template rendering:
In template /Users/mac/myfirstproject/templates/base_layout.html, error at line 12
Reverse for 'list' not found. 'list' is not a valid view function or pattern name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ARTICLES</title>
<link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
<div class="wrapper">
<h1><img src="{% static 'logo.png' %} "/></h1>
{% block content %}
{% endblock %}
</div>>
</body>
</html>
As indicated in Andrei's comment above, you need to make sure you have 'list' set up as a valid url name in your urls.py file.
something like this:
urls.py
from django.conf.urls import url
from .views import list_view
urlpatterns = (
url(r'^list$', list_view, name='list'),
)
in order to use the {% url 'url_name' %} template tag, you have to have a url named url_name, and if you have your project divided into apps, the format is:
`{% url 'app_name:url_name' %}. If you post your urls.py file, perhaps we can be more helpful.

Using user CSS sheet in a template

I'm using Django to display user uploaded static HTML and CSS files. The HTML isn't a problem, however I can't get Django to actually render using the uploaded CSS.
Project structure is the following:
my_project
main_app
display_app
my_project
media
user
whatever.html
whatver.css
My main url.py contains:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^html_uploads/', include('display_app.urls')),
url(r'^', include('main_app.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
display_app urls.py is:
urlpatterns = [
url(r'^(?P<requested>(?:[\w]+\/?)+)$', views.readhtml, name='requested'),]
The relevant part of the view is:
def read_html(request, file_name):
title = 'html_file_title'
body = get_body(file_name)
css_source = 'user/whatever.css'
return render(request, "display_app/base.html",
{'title': title,
'body': body,
'css_source': css_source,
'media_url': settings.MEDIA_URL,}
)
The CSS simply contains:
body {
background-color: #FFCC66
}
And the template looks like:
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ media_url }}{{ css_source }}" type="text/css" />
</head>
<body>
{% autoescape off %}
{{ body }}
{% endautoescape %}
</body>
With this, I get a 404 as Django fails to find /media/user/whatever.css.
If I change the CSS location to:
<link rel="stylesheet" href="/{{ media_url }}{{ css_source }}" type="text/css" />
The 404 warning disappears, the HTML still loads, however the CSS is silently ignored.
The HTML is passed through several functions and heavily modified, therefore passing it as a string made sense, however the CSS should be used directly and I was hoping to load it from the template instead.
What's going on there? Does not getting a 404 warning mean Django is locating the CSS file correctly? If it is, why is it not used?

Django 1.8 and the ever confusing "Static Files"

I've fired up a new Django 1.8 project and am hitting the wall of trying to serve static files in the development environment. I'm pretty sure I've followed the docs explicitly, but it's just not working.
Settings.py
STATICFILES_DIR = (
os.path.join(BASE_DIR, 'static/'),
BASE_DIR
)
STATIC_URL = '/static/'
STATIC_ROOT = '/srv/www/cpm2/static/'
urls.py:
from django.conf.urls import include, patterns, url
from django.conf import settings
from django.conf.urls.static import staticĀ·
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^test/', TemplateView.as_view(template_name="basics/base.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates/basics/base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load staticfiles %}
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
When I go to http://my_server_ip:8000/test/ none of the CSS is loaded. Viewing the page source, I see this where that CSS link is <link href="/static/css/bootstrap.css" rel="stylesheet"> which is good, but when I try to follow that link directly, it fails giving me a 404 error.
Now, I've set up my Apache server to serve the files directly, they work. So, going to http://my_server_ip/static/css/bootstrap.css works - so I know the files are readable. It's just they don't work in development.
What am I doing wrong? As so many others before me, I'm pulling my hair out!
EDIT Trying to access the file directly gives me this:
Page not found (404)
Request Method: GET
Request URL: http://my_server_ip:8000/static/css/bootstrap.css
Raised by: django.views.static.serve
'css/bootstrap.css' could not be found
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
It doesn't even show a list of places its tried, just that the file isn't found.
You are missing an 's' from STATICFILES_DIRS.
Also, you shouldn't be including your BASE_DIR in that setting - that could end up serving all your python code, which would be a bad idea.