I want to apply CSS on my Django project.
CSS path in my index.html is right but it doesn't work well.
My index.html page show up well in my site,
--app_index
----index.html
----bootstrap
-------css
-----------abc.css
-----------abc2.css
So, must I modify the URL.py file too?
You need to configure static files in your Django app. The following links should help guide you in the right direction:
http://www.tangowithdjango.com/book/chapters/templates_static.html
https://docs.djangoproject.com/en/1.7/howto/static-files/
You will set up your index.html for example in a template directory that can access your static files (e.g. CSS, javascript, static images, etc.) that are located in your static directory.
In response to your question concerning modification of urls.py, the answer is yes. As you will see in the links on configuring static files within your project, you have to add some code to your urls.py. An example of this code might look like this:
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
url(r'^__debug__/', include(debug_toolbar.urls))
)
During development Django serves your static files hence the above code, but during production your static files are served via your configured server (e.g. Apache, nginx).
Related
This is my folder structure
Music
-Music
-Feature
-static
-feature
core.css
-css
other css files
-js
-img
-templates
404.html
500.html
index.html
-feature
about.html
detail.html
template.html
manage.py
views.py
from django.shortcuts import render
def error404(request):
return render(request,'404.html')
urls.py
urlpatterns = [
url(r'^featured/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^about/$', views.about, name='about'),
url(r'^FAQ/$', views.faq, name='faq'),
]
handler404 = 'mysite.views.error404'
The custom 404.html file gets rendered but with no css.And normally the css works fine on other pages but when I set debug=falseto check the custom 404 error page in settings.py the css for the entire project disappears. Something to do with folder structure or some other problem?
edit: core.css is the main css file and the part with other css files contains css for plugins
It's about serving static files. When you use DEBUG = True then django takes care about them otherwise your server should do it. Django in debug mode uses this view. The warning from there:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure.
This is only intended for local development, and should never be used
in production.
You can run your server with --insecure option just to test 404 error or you can explicilty create url for that page to check its styling:
Use the --insecure option to force serving of static files with the
staticfiles app even if the DEBUG setting is False. By using this you
acknowledge the fact that it’s grossly inefficient and probably
insecure. This is only intended for local development, should never be
used in production and is only available if the staticfiles app is in
your project’s INSTALLED_APPS setting. runserver --insecure doesn’t
work with CachedStaticFilesStorage.
Your handler404 and view are okay. But you don't need them. Just a custom 404 template is enough. See: https://docs.djangoproject.com/en/1.8/topics/http/views/#the-http404-exception
In order to use the Http404 exception to its fullest, you should
create a template that is displayed when a 404 error is raised. This
template should be called 404.html and located in the top level of
your template tree.
The template is in the right location. I think the problem is serving your static files. Open developer tools in your browser to see what resources fail to load (console, network or sources tab). Inspect the paths. Is there an external style sheet link in the head section of the 404 source? (elements tab or view source code).
https://docs.djangoproject.com/en/1.8/howto/static-files/
I have a problem about serving admin uploaded files in my templates.
I set:
MEDIA_URL='/media/'
MEDIA_ROOT = 'assets/'
and my models are like:
mainPhoto = models.ImageField(upload_to="articles/")
When in my templates, I try:
<img src="{{MEDIA_URL}}{{article.mainPhoto}}" />
The image doesn't show up on the website.
I found one deprecated solution with the django .serve(), but I hope to avoid using it.
I was looking everywhere and didn't find any answer, so I hope someone here will be able to help me.
There are two parts to make this work. First is the Django configuration. There are really two settings for this which you have already mentioned - MEDIA_URL and MEDIA_ROOT. As already noted in the comments the MEDIA_ROOT has to be an absolute path. For example:
MEDIA_ROOT = `/abs/path/to/project/media/`
Second part is actually serving the files. If you are in production, you NEVER want to serve your static or media files through Django so you should configure Apache or nginx or whatever server system you are using to serve the files instead of Django. If you are on the other hand still developing the app, there is a simple way to make Django serve media files. The idea is to modify your urls.py and use the Django's static files server to serve media files as well:
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# other patterns
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
More about this approach at Django docs.
Also FYI, you probably should not use {{MEDIA_URL}}{{article.mainPhoto}} to get the url of an image. This approach will break for example if you will no longer use file system storage for static files and will switch to something different like Amazon S3. It is always a good idea for the storage backend to figure out the url:
<img src="{{article.mainPhoto.url}}" />
I've looked through countless answers and questions trying to find a single definitive guide or way to do this, but it seems that everyone has a different way. Can someone please just explain to me how to serve static files in templates?
Assuming I've just created a brand new project with Django 1.4, what all do I need to do to be able to render images? Where should I put the media and static folders?
Put your static files into <app>/static or add an absolute path to STATICFILES_DIRS
Configure your web server (you should not serve static files with Django) to serve files in STATIC_ROOT
Point STATIC_URL to the base URL the web server serves
Run ./manage.py collectstatic
Be sure to use RequestContext in your render calls and {{ STATIC_URL }} to prefix paths
Coffee and pat yourself on the back
A little bit more about running a web server in front of Django. Django is practically an application server. It has not been designed to be any good in serving static files. That is why it actively refuses to do that when DEBUG=False. Also, the Django development server should not be used for production. This means that there should be something in front of Django at all times. It may be a WSGI server such as gunicorn or a 'real' web server such as nginx or Apache.
If you are running a reverse proxy (such as nginx or Apache) you can bind /static to a path in the filesystem and the rest of the traffic to pass through to Django. That means your STATIC_URL can be a relative path. Otherwise you will need to use an absolute URL.
The created project should have a static folder. Put all resources (images, ...) in there.
Then, in your HTML template, you can reference STATIC_ROOT and add the resource path (relative to the static folder)
Here is the official documentation:
How to manage static files: https://docs.djangoproject.com/en/1.4/howto/static-files/
Static Files in general: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/
If you are planning to to deploy in a production type setting then you should read the section here: https://docs.djangoproject.com/en/1.4/howto/static-files/#staticfiles-production
Generally you put our static and media folders outside of the django project app
Define your STATICFILES_DIRS, STATIC, and MEDIA path in the settings.
Create staticfiles folder beside your templates folder, urls.py, settings.py, etc...
You don't have to create media folder because it will automatically created when you upload images.
In your urlconf put this one:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
.............
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
In templates:
{% load static %}
<img src="{% static 'images.png' %}">
<img src="{{MEDIA_URL}}images.png">
I'm using http://appfog.com I have DEBUG = True and ADMIN_MEDIA_PREFIX = '/static/admin/'
The css for the admin is missing.
Django only serves static files if DEBUG=True and it is running the development server.
Documentation:
This view is automatically enabled and will serve your static files at STATIC_URL when you use the built-in runserver management command
[...]
To enable this view if you are using some other server for local development, you'll add a couple of lines to your URLconf. The first line goes at the top of the file, and the last line at the bottom.
Example:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
Hope this helps
Using dbieber's Django template for appfog this is the approach that worked for me:
Create a directory for static files in your project directory, then set up a URL to have the appfog server serve these files:
cd <project>
mkdir static
In urls.py, make sure the urlpattern is set to include static files (this is already there if you use the template):
urlpatterns += patterns('',
...
url(r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.STATIC_ROOT),
)
Collect all static files into the static directory
python manage.py collectstatic
Deploy to appfog
af update <appname>
This should be super simple, but somehow its has had me stuck all morning. I'm developing locally, using the django debug server, and with this filestructure:
/project/ (django project)
/static/ (static files)
In the settings.py MEDIA_ROOT and MEDIA_URL are both set to '/static/' and I'm using this in my urls.py
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
In my templates, the files that need to be server from the static directory are configured as such:
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">
That all works as it should - the javascript/css/images are all served properly from the hompage. However, when I go to a subdirectory, such as http://127.0.0.1:8000/news/ then all the links are broken.
I've tried using a variety of the os.import options to get it to do the relative links properly, but havent had any luck. Is there a way that I could force it to be relative to the base url, or perhaps hardcode it to my filesystem?
Any help would be amazing!
In this line in your urls.py file, the '../static' should be changed to an absolute directory. Try changing it and see what happens.
Your file:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '../static'}),
Should look more like:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/full/path/to/static'}),
To give you an example, mine is set up a little differently, but I still use a full path.
Here's how mine is setup:
in settings.py
STATIC_DOC_ROOT = '/Users/kylewpppd/Projects/Django/kl2011/assets/'
and in urls.py:
(r'^assets/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes':True}),
I'm serving my static files from 'localhost:8000/assets/'.
I just had the same problem, and I solved it by removing first slash from STATIC_URL='/static/' and making it STATIC_URL = 'static/' just like philipbe wrote above.
Wierd thing is that '/media/' works fine for MEDIA_URL at the same time (while 'media/' breaks layout).
Anyway - just change STATIC_URL to be equal to 'static/' with no leading slash, and you'll solve it.
How do your links break when you go to a subdirectory? Can you explain that further please.
Does django 1.3 support some kind of strange relative url routing for static media?
If it can be served from the homepage but not others, doesn't that sound exactly like your STATIC_URL is a relative location?
What is your STATIC_URL? It should be absolute and start with a slash.