I have a new django project called mysite. Inside mysite is a folder called static, where all my images are.
Inside mysite is also a templates folder with a file named index.html with the the following basic code:
<html>
<head></head>
<body><img src = WHAT GOES HERE?? />
</html>
I have this views.py file in my mysite folder:
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html',)
In my settings.py file, STATIC_URL = '/static/'
What is the exact text that should go inside my img tag to correctly reference the static image file (note: I am not looking for links to documentation). And do I need to change any of the folder/settings structure? Thank you.
I have added the following tag:
< img src="{{STATIC_URL}}logo.jpg"/>However, it still does not load -- it seems to be going to the correct path though (image path in the browser says 127.0.0.1:8000/static/logo.jpg.). What do I need to change so this开发者_如何学C loads correctly? And I have checked to make sure the image is at that location.
UPDATE: this is how I finally got it to work:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': sttings.MEDIA_ROOT}),
)
(I'm using the media_url instead of the static_url). Is there an easier way to do this?
David542,
Your structure should be something like follows.
MyProject
\MySite
\static
This static folder will be served when you use runserver. When you move your work into a production environment you would want to use django's ./manage.py collectstatic
and be sure to serve your static media at the static url you specified in your settings.py file. So if you have an image in your static folder you should be able to reference by saying /static/some_image.png
Staticfiles was not included with Django until version 1.3. If you're older than 1.3 that would explain why your current set up is not working for you. (I'm guessing this is your problem.)
Hope this helps.
Edit: And if serving by typing out your path is all working for you and your comfortable you should indeed use what another answer said and use {{ STATIC_URL }}hi.jpg
as if you choose to change your static url you will not have to change your templates to match since they'll work automatically.
If the image is called "hi.jpg", it would look like this:
img src="{{ STATIC_URL }}hi.jpg"
That would resolve to a file uploaded into the STATIC_URL directory, in your example that would be:
/static/hi.jpg
First, read the documentation on serving static files, then, when you feel as if you understand the concepts behind serving static files locally and in production, read the docs once more.
Then make sure you've added django.contrib.staticfiles
to your INSTALLED_APPS
.
If the image is called "pic.jpg", it would be
img src = "{{'static/pic.jpg'}}"
This worked for me...also check that
django.contrib.staticfiles
, in installed_apps of settings.py
精彩评论