When exactly do I need staticfiles_urlpatterns - django

currently I am dealing with django static/staticfiles and I learnt a lot about static_url, static_root, staticfiles_dirs here at stackoverflow and in youtube tutorials.
However I don't understand what "staticfiles_urlpatterns" does and when exactly I have to use it?
Thanks for an answer.

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Your question is what does it have to do with urls.py file?
Well i believe you must know about absolute_urls and how they're constructed. well similarly prior to Django 2.0 we had to do this to tell that our static request to go to settings.py and look for static variables which are then pointing to staticstorage, eg , STATIC_ROOT & STATIC_URL
You don't need to add the following lines to the project's url.py in Django 2.0 because Django knows that it has to prefix the static file url path in the template with STATIC_URL:
urls.staticfiles_urlpatterns()
This will return the proper URL pattern for serving static files to your already defined pattern list. Used like this:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()

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)

Django Models.filefiled file dosent exist

I wish to access the file i upload using models.FileField(), but its shows different path when i click on the link provided in the admin page. May i know what's the problem here?
Updated my code, but the url dosent seem corret. getting a 404 code error.
you need to declare MEDIA_ROOT = os.path.join(BASE_DIR,'media')
and add them to the urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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/

My DJango app is responding to /static urls

Update
I figured out what was causing the stylesheets to become invisible, though I don't quite understand it all. I set DEBUG=False in settings.py to test the error handling as described in the tutorial. Somehow setting debug to false causes the static files not to be locatable. I will look further in the configs to see if I can get a clear understanding why. Until then, please feel free to answer or comment with additional info. I am still learning!
Update
I'm going through a DJango tutorial from here and I hit a roadblock. I'm up to tutorial 3 where they explain how to refactor your urls.py file when I try loading up the admin site to make sure I haven't broken it. Sure enough it looked all wierd because it was missing the stylesheets. Stylesheets are pulled from here:
http://127.0.0.1:8000/static/admin/css/base.css
When I hit that link in my browser I get the custom 404 page I configured for my app. The stylesheets were working prior but I'm not sure which change broken them. I went through my urls.py file and reverted all of the polls specific url configs to no avail. Here's my current urls.py under hellodjango (the name of my project.)
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.http import HttpResponse
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
def page_not_found(request, template_name='404.html'):
return HttpResponse("Could not find the resource you asked for...")
handler404 = 'hellodjango.urls.page_not_found'
and here's the urls.py under my polls directory:
from django.conf.urls import patterns, url
# Uncomment the next two lines to enable the admin:
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
Help?
It looks like you don't have a URL pattern for /static. As such, the static/admin/css/base.css URL doesn't match any pattern, and so you get a 404. Try something like this:
from django.conf.urls.static import static
# ...
urlpatterns = patterns('',
# ...
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
# ...
This should work for you -- go to /static/foo.css, and you should see your CSS.
It's worth noting that this is discouraged in a production environment. For your tutorial app, though, it'll work.
The staticfiles app provides a custom runserver management command that automatically serves the static files, are you sure you have the following in your settings?
INSTALLED_APPS = (
# ...
'django.contrib.staticfiles',
)
In production, you'll use the collectstatic management command that finds all of the static media and dumps it into STATIC_ROOT (this is the only purpose for this setting - it isn't used or needed during development).
Glad you figured it out. Here's why it works like this.
django.contrib.staticfiles overrides the runserver management command so that the static files are served automatically. To remind people that they shouldn't be using django to serve static files, this only happens when DEBUG = True, as you found out.
The documentation of the overridden management command explains that you can use the --insecure flag to make this work no matter the state of the DEBUG setting.

Django favicon.ico in development?

How can I serve favicon.ico in development? I could add a route in my urlconf, but I don't want that route to carry over to the production environment. Is there a way to do this in local_settings.py?
The easiest way would be to just put it in your static directory with your other static media, then specify its location in your html:
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
My old answer was:
You can set up an entry in your urls.py and just check if debug is true. This would keep it from being served in production. I think you can just do similar to static media.
if settings.DEBUG:
urlpatterns += patterns('',
(r'^favicon.ico$', 'django.views.static.serve', {'document_root': '/path/to/favicon'}),
)
You also could just serve the favicon from your view.:
from django.http import HttpResponse
def my_image(request):
image_data = open("/home/moneyman/public_html/media/img/favicon.ico", "rb").read()
return HttpResponse(image_data, content_type="image/png")
This worked for me:
from django.conf.urls.static import static
...
if settings.DEBUG:
urlpatterns += static(r'/favicon.ico', document_root='static/favicon.ico')
From the docs:
from django.conf.urls.static import static
urlpatterns = patterns("",
# Your stuff goes here
) + static('/', document_root='static/')
There doesn't appear to be a way to serve a single static file, but at least this helper function is a wrapper which only works when DEBUG = True.
I use this:
from django import conf
from django.conf.urls import static
...
if conf.settings.DEBUG:
urlpatterns += static.static(
r"/favicon.ico", document_root=conf.settings.STATIC_ROOT / "favicon.ico"
)
Well, you can create your own loader.py file, which loads settings you want to override.
Loading this file should look like this:
try:
execfile(os.path.join(SETTINGS_DIR, 'loader.py'))
except:
pass
and be added at the end of settings.py.
This settings should not be commited into production server, only should appear on development machines. If you are using git, add loader.py into .gitignore.