I must be missing something.
So this should be how my folder does look:
Obviously with the asked image.
To increase portability, I use dynamic path in the code.
The code in settings.py
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango'
urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),url(r'^rango/', views.about, name='about'))
views.py
def index(request):
context = RequestContext(request)
# Construct a dictionary to pass to the template engine as its context.
# Note the key boldmessage is the same as {{ boldmessage }} in the template!
context_dict = {'boldmessage': "I am bold font from the context"}
# Return a rendered response to send to the client.
# We make use of the shortcut function to make our lives easier.
# Note that the first parameter is the template we wish to use.
return render_to_response('rango/index.html', context_dict, context)
def about(request):
return HttpResponse("Rango says: This is about page!<a href='../../'>Index</a>")
Note that the image is put on a html template. The html is ok (loaded), but the image dont.
<!DOCTYPE html>
{% load static %} <!-- New line -->
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Rango says...</h1>
hello world! <strong>{{ boldmessage }}</strong><br />
About<br />
<img src="{% static "rango.png" %}" alt="Picture of Rango" /> <!-- New line -->
</body>
</html>
Result?
The image got returned by a nasty 404
Accessing from 127.0.0.1:8000/static/rango.png or manage.py findstatic rango.png will result a failure.
However, accessing from file:///D:/tango_with_django_project/static/rango.png will be successful.
Thanks
Aditional information:
DEBUG=TRUE
I had checked STATIC_PATH, file did lead to the right path D:\tango_with_django_project\static
Is it possible due to backslash and forward slash, but if the slash is the problem, then the template should also broken.
In production static files should be served by the web server and not by django itself. That's why it is not enabled by default.
You need to say to the development server that it must serve the static files. I think that setting DEBUG=True in your settings.py should be enough.
You may also need to add this in your urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'your_app.views.home', name='home'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls))
)
if settings.DEBUG :
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'^static/(?P<path>.*)$', 'serve'),
)
I hope it helps
The problem may have to do with a lack of finders for the app's directory. Add the following to the project's setting.py:
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
Related
I need to connet JS custom files, images, css files to my project, but i meet 404 error.
REQ
asgiref==3.6.0
Django==4.1.4
sqlparse==0.4.3
tzdata==2022.7
MY DIR
enter image description here
MY SETTINGS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'car_manage',
]
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MY INDEX.HTML FILE
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all">
<script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script>
MY URLS
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MY VIEWS
def get_acc(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
number = form.cleaned_data['number']
cache.set('number', number)
Account.objects.create(**form.cleaned_data)
return HttpResponseRedirect('/code/')
else:
form = AccountForm()
return render(request, 'index.html', {'form': form})
I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any.
When I try to find static with the command:
`python manage.py findstatic car_manage/js/jquery-1.10.2.min.js`
I see this:
WARNINGS:
?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist.
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
I tried to change my settings file to:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
After that i see:
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
But it didn't solve my problem, still error 404
You need to serve static files as well, so:
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
Try this way:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'car_manage/static/'),
)
I'm having issues getting an image to load on my Django web application. I have used the online documentation and tried peoples suggestions that I found on Stackoverflow but I am still not having any luck getting it to load. Here is what I have:
Settings.py:
STATIC_DIR = os.path.join(BASE_DIR,'static')
INSTALLED_APPS = [
...
'django.contrib.staticfiles'
]
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,]
Urls.py:
from django.urls import path
from dir_app import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'dir_app'
urlpatterns=[
path('', views.tradesmen, name='tradesmen'),
path('register', views.register,name='register'),
path('user_login', views.user_login,name='user_login')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Index.html: (Gist)
<!DOCTYPE html>
{% load static %}
<html>
<head>
</head>
<body>
<img src="{% static 'dir_app/tools.png' %}">
</body>
</html>
Here is where the image is stored:
DEBUG should be true if want to use django.conf.url.static
https://github.com/django/django/blob/926148ef019abcac3a9988c78734d9336d69f24e/django/conf/urls/static.py#L23
STATIC_ROOT should be a string, not a list.
https://docs.djangoproject.com/en/3.0/ref/settings/#std:setting-STATIC_ROOT
Django STATIC files does not work in Develop mode.
I tried in many ways, but I did not succeed.
Could someone tell me where I'm wrong?
Thank you very much for your attention.
STATIC_URL = '/static/'
STATIC_ROOT = "/Users/user/Projects/RMA/static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '..', 'static'),
)
....
'django.contrib.staticfiles',
routes
urlpatterns = [
url(r'^$', views.index, name='index')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
View
def index(request):
return render(request, 'base.html', {'question': 'ads'})
template
{% load static %}
<link href="{% static 'site/bower_components/select2/dist/css/select2.min.css' %}" rel="stylesheet">
I know this is a repeated question, but I am unable to find any answers that would make the static files run for me. I am using Django version: 1.10.5 and python version: 3.4.3...
I have read the official documentation too, no luck in solving my problem...
The following is my project structure:
myproject4
/myapp/
/__pycache__/
/migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
/myproject/
/__pycache__/
__init__.py
settings.py
urls.py
wsgi.py
/static/
/css/
hpage.css
robot.css
/images/
-- Images --
/js/
-- JavaScript Files --
/template/
hello.html
manage.py
Here's what all I have tried:
{% load staticfiles %}
for my hello.html page, right at the top,
<link href="{%static 'css/hpage.css' %}" rel="stylesheet" />
<link href="{%static 'css/robot.css' %}" rel="stylesheet" />
for linking my CSS files in hello.html (it makes use of 2 CSS files).
I have tried {{ STATIC_URL }} way of doing the same and the necessary stuffs I am supposed to do too, but found no luck there.
When I use the <style> </style> tags, the css works perfectly, but that's not what I am looking for.
settings.py:
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
#Other stuffs go here
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/static/',
)
urls.py:
from django.conf.urls import url,include
from django.contrib import admin
from myapp.views import hello,user_profile
from myapp import views
admin.autodiscover()
urlpatterns = [
url(r'^admin/$', admin.site.urls, name='admin'),
url(r'^hello/$', views.hello, name='hello'),
url(r'^hello/user_profile/', views.user_profile, name='user_profile'),
]
views.py:
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext
def hello(request):
return render_to_response('hello.html')
def user_profile(request):
return render_to_response('user_profile.html')
Kindly guide me where I am going wrong...
Thank You in advance :)
EDIT: In my settings.py file, DEBUG = False because I have a file called 404.html that gives out the error page for me as default.
These are the steps I have followed to include CSS to my Django Project:
First, I have added in the settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
Second in the urls.py (app folder)"
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Copied all CSS files in the Project folder (same level with manage.py)
Include/Declare CSS in a template (I included mine in base.html)
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'assets/css/bootstrap-theme.css' %}" media="screen" >
<link rel="stylesheet" href="{% static 'assets/css/main.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/style.css' %}">
</head>
Run:
python manage.py collectstatic
and reload/restart the browser or delete cache.
Make changes to urls.py like bellow. and look at documentation for your ref.
from django.conf.urls.static import static
urlpatterns = [
rl(r'^admin/$', admin.site.urls, name='admin'),
url(r'^hello/$', views.hello, name='hello'),
url(r'^hello/user_profile/', views.user_profile, name='user_profile'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In Django 1.8, I can upload images and they are saved on the path that they should, but when I add <img src="{{ slider.Image.url }}" alt="Slider" /> to template, the images are not displaying. If I want to see only the image like this http://127.0.0.1:8000/static/images/slider/1.jpg in the url the image does appear. But when I go to the home page http://127.0.0.1:8000/home/ it only show me the alt.
Here is my dir tree:
- home
- static
- static/
css
images
slider
js
The images placed properly in slider. CSS and Js working properly.
Here is my settings file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home'
)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = (
'static/'
)
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'static')
)
When I use static_root the problem get more serious nothing worked.
Here is my models in home for slider
class Slider(models.Model):
ImageName = models.CharField(max_length=200)
Image = models.ImageField(upload_to="images/slider")
Here is my main urls
from django.conf.urls import include, url, patterns
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', include('home.urls')),
]
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),
)
Here is my home app urls
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.slider, name='slider',)
]
Here is my template source
{% for slider in sliders %}
<li class="item"><img src="{{ slider.Image.url }}" alt="Slider" /><span class="overlay1"></span></li>
{% endfor %}
You shouldn't mix static and media files. Static files are CSS, JavaScript, Images and other files that comes in package with your app, so it can work properly or to look nice.
Media files are files uploaded from website or just files associated with some objects in database.
That files shouldn't be mixed.
Also, STATIC_ROOT and STATICFILES_DIRS shouldn't point at same directory. All files from STATICFILES_DIRS and files from static directories inside each app will be copied or linked into STATIC_ROOT when ./manage.py collectstatic is executed.
Django development server by default won't serve any media files, if you want them to be served, add to your main urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)