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.
Related
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)
I have put some static files for CSS Javascript and Jquery in my file static.
I have put load static in my HTML and it doesn't respond properly to the HTML.
Do you have anything else to do with it?
output error
setting.py file
Problem is that you have not added /static/ urls to your urls.py and set STATIC_ROOT in your settings equal to path to your static files:
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)
You can see it in docs: https://docs.djangoproject.com/en/3.2/howto/static-files/#serving-static-files-during-development
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
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!
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/