Static Files With Django 1.6 - django

I have spent all day and nothing works. I have seen at least 20 posts here about the same topic and they are different with different suggestions and nothing works for me.
Running Django 1.6 with Python 2.7.+
I'm trying to load the css for the polls app from the django tutorial.
project layout
Project
|-polls
|-static
|-polls
style.css
|static
here is the settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/static'
template code
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
urls.py
urlpatterns = patterns(...)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
polls/urls.py
urlpatterns = patterns(....,url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),)
After running: python manage.py collectstatic, everything is collected and static folder which is on root gets populated accordingly with the admin and polls folders and files.
I start the server: python manage.py runserver everything works fine except the css is not loaded
this is what i get from the Chrome console when i inspect the html
....
<link rel="stylesheet" type="text/css" href="/static/polls/style.css">
....
which looks fine but gives the following output
[16/Nov/2013 00:44:41] "GET / HTTP/1.1" 404 2141
[16/Nov/2013 00:44:45] "GET /polls/ HTTP/1.1" 200 820
[16/Nov/2013 00:44:45] "GET /static/polls/style.css HTTP/1.1" 404 1649
Any help would be appreciated. I followed everything step by step. I don't know what to do anymore
UPDATE
DEBUG=True
full urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from PoolsDjangoProject import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'PoolsDjangoProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
full polls/urls.py
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(),name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='votes'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),
)
And when i try to access
http://127.0.0.1:8000/static/polls/style.css
I get
Page not found (404)
'polls/style.css' could not be found

I found it necessary to restart the running server after following the steps in
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
in order to pick up the newly created static directory. That step isn't listed in the tutorial. I have opened a ticket requesting its addition.
I realise this answer is not likely to help your specific case but this question comes up prominently in Google when searching for problems with adding a static directory to the example Polls app.

I ran into this problem too. My problem was that I didn't have my main app in the installed apps, whatever folder that has wsgi.py in it, that needs to be in INSTALLED_APPS.

I struggled with this problem as well.
Here's how I solved it (DEBUG=True):
After creating a project and several apps, I created a directory called "static" that sat alongside my app directories (same level as .manage.py).
I set my static URL to '/static/' in settings
I set my static root to STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/')) (BASE_DIR = os.path.dirname(os.path.dirname(__file__)))
I set my staticfiles dirs to STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), '/Users/username/sites/containing_dir/project_dir/static/',) (assumes OSX path)
I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py for my project
My static media is now served from http://127.0.0.1:8000/static/css/styles.css (assuming runserver command).
Comment if you need addition description!

Firstly it has to be known that Django is not responsible for serving static files on production servers. However, it does serve them when DEBUG=True during development for the sake of debugging.
For serving static files when debug=true you have to do nothing. I don't know why it is creating confusion among newbies on how to setup it. The below should help you create static files for both production and dev modes clearly
Development mode : when DEBUG=True
create your project django-admin.py startproject mysite
create your app manage.py createapp myapp
Add myapp to INSTALLED_APPS in settings.py
In myapp dir, create a folder static
In the myapp/static dir, save a file myfile.css
In settings.py, provide a valid address to STATIC_ROOT folder to store static files. It could be something like os.path.join(os.path.abspath(os.path.dirname(__file__)), "mystatic") if you want to store your collected files at mysite/mysite/mystatic.
run manage.py collectstatic; now you have to see the static file collected at the directory you mentioned above..It should also create one if its not present. You are free to put any directory.
test the url http://127.0.0.1:8000/static/myfile.css
In case if its not working yet, try restarting the site.. New files are not recognized dynamically!

Related

Django project is not reading my static css file

I am working on a django project and for some reason the style.css file is not read. However, my static images are working. Not really sure what the issue is, any help is greatly appreciated. There are also no errors showing in the console and terminal..
Link to my github repository
https://github.com/Amanuel763/petwebsite
Add STATIC_URL and STATIC_ROOT to your urls.py. See more about Serving static files during development[Django-doc]
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)

How do I get Django to load my favicon from my React build directory?

I am using Django and React to create a web application. When it comes to my React Development server, my favicon.ico loads like it should, but when I build my files, my Django development server doesn't find and render my favicon, and I have no idea why. I've tried renaming my favicon and changing the file type to .png. When I put my favicon into my static directory, and change the file name from favicon to some thing like "icon.ico", then it loads properly. But, I can't have my favicon in my static directory because CRA won't copy it into that directory when it builds. It's probably something small and simple so I'll show y'all all of the related files. Thanks for any insight!
EDIT: I tried collectstatic , but that did not help
EDIT 2: using {% load static %} but this doesn't work because my favicon is in the same directory as my html file. I should also clarify that import links to the parent directory that holds both my html file and my favicon file don't register for some reason.
The import in my build/index.html: <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico"/>
urls.py
from django.contrib import admin
from django.urls import include, path, re_path
from django.conf.urls import include, url
from backend import views
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('backend.urls')),
path(r'^api/<int:pk>$', include('backend.urls')),
path(r'^api/<int:pk>$/', include('backend.urls')),
url(r'^.*$', views.index),
]
my settings.py static settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(FRONTEND, 'build/static/'),
]
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
)
Also, let me know if the problem could be in another file
The problem is that the django url routing has no access to the favicon.ico since CRA puts it in /build and all your static files are served from /build/static.
Assuming you haven't ejected, a hacky solution is to copy the favicon.ico into the static folder in your build step in package.json scripts section:
"build": "react-scripts build && cp build/favicon.ico build/static/favicon.ico"
and then in the html template in /public, set the favicon.ico url to
<link rel="shortcut icon" href="/static/favicon.ico">
instead of %PUBLIC_URL%/favicon.ico.
If you have ejected the CRA, you can update your webpack config to move the favicon.ico directly into /build/static

Django 2 media returns error 404 (top level media folder)

Running Django 2.1.5 with Python 3.7.2 32-bit, Win10 localhost, no nginx etc. Cloned the repo https://github.com/axelpale/minimal-django-file-upload-example.git
Can upload files and they appear as a url link in the db and as a list item on the page but the images/files do not display on the page and return 404 in the console.
Error returned:
GET http://127.0.0.1:8001/media/documents/2019/04/07/image.jpg 404 (Not Found)
I can see the file at that location in explorer.
The code is exactly as per the repo with the addition of the following:
list.html line 14
<li><img src="{{ document.docfile.url }}" height="60px"></li>
and
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ path('', views.list, name='list')]
I have followed the documentation as far as I can and looked at other SO post that suggest the static pattern should go first.
It should be noted that the media folder is at the top level of the directory.
for_django_2-0
-myproject
--myproject
--media
--myapp
Also:
DEBUG = True
Have tried running with:
python manage.py runserver 8001 --insecure
and
python manage.py runserver 8001
Any help would be much appreciated.
Thanks, Jon
To answer my own question, after some more digging on another topic I found this useful video.
https://www.youtube.com/watch?v=PIvlcmnayOE&t=55s
The video explains something I missed in the other tutorials. Your static urls path needs to be in the root project urls.py not the app urls.py
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls'))
This now works.

Loading images in a static file

So I have completed the Django tutorial, play around with it some, and feel that I have a good understanding of Django. The only problem I am facing is that when I try to display a static page for a landing page, I cannot seem to get any images to load.
First off I have tried two different methods of displaying a static landing page.
First:
# main app urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="landing/index.html")),
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
This is the main app's urls.py and I use the TemplateView to display the static index.html which is located at 'my_app/templates/landing/index.html'.
This is all and well until I try to add a static image into the index.html file. No matter where I put the image file I cannot seem to get it to display. In the index.html template I have tried different methods of using static as well as trying different direct paths without the need for the embedded python code. How am I supposed to display images and where should they be located?
The second method I found that worked for just displaying the static page (not the image) was to create a new app called landing and have that simply display a static page from the urls.py in the same manner(using TemplateView). Is this method better? I still had the same problems in displaying an image within the static page as the first method, which makes me think it has something to do with the TemplateView.
Am I doing this completely wrong? What are my options? I am using Django 1.5.1.
Thanks in advance!
It is a bit awkward to serve statics files with Django. This is because they have the conception that static files such as images must be in another domain or server for performance/security reasons.
To serve static content with django do this:
# urls.py
# add this lines at the end
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then in settings.py define the directory where the images/css/js and similar static contents are:
# settings.py
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# this assumes your static contents is in <your_project>/static/
os.path.join(PROJECT_ROOT, 'static/'),
)
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
Note: You may also consider images as media and place them in your media/ folder.
That should get static files served with your app. Just reference them like this href="/static/xxxx.jpg" or href="/media/xxxx.jpg".
Hope it helps!
This blog explains serving static file and might help:
http://agiliq.com/blog/2013/03/serving-static-files-in-django/

django and static css plus js files

i did a small app on django and it is using templates. Each tempalate use static files such as css, js and images. all those files in same directory as template.
template
main.html
support.html
about.html
...
css
reset.css
style.css
...
img
js
jquery.js
main.js
...
if there is was to configure django development server to load those files without editing html templates files?
i am receiving
http://127.0.0.1:8000/face/css/960_24_col.css 404 NOT FOUND 127.0.0.1:8000
this changes in settings.py didnt help me
STATIC_ROOT = 'C:/Projects/site/website/face/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('C:/Projects/site/website/face/static',)
You might want to use the contrib app staticfiles. At the bottom of the doc page you'll see how to use it on development server.
STATIC_URL has been defined as '/static/' so all static files will be served from /static.
In other words /face/css/960_24_col.css is incorrect.
This should be /static/face/css/960_24_col.css , assuming the face directory is located at C:/Projects/site/website/face/static/face.
Might I also advise you not to use absolute paths in your settings file. To find out the absolute path of the root of your project use something like:
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
Here is how I serve static files via the Django dev server.
Defined in urls.py:
from os import getcwd, path as ospath
...
urlpatterns += patterns('',
(r'css/([a-zA-Z0-9_.]+.css)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'css')}),
(r'images/(.*)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'images')}),
(r'js/([a-zA-Z0-9_.]+.js)$', 'django.views.static.serve', {'document_root': ospath.join(getcwd(), 'js')})
)