I am following the Django 1.6 tutorial on how to work with static files (https://docs.djangoproject.com/en/1.6/howto/static-files/). However, something is not working...
This is what I have so far...
URLS:
#mysite/urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^myapp/', include('myapp.urls')),
)
#mysite/myapp/urls.py:
from django.conf.urls import patterns, include, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
VIEWS:
#mysite/myapp/views.py:
from django.shortcuts import render
def index(request):
return render(request, 'myapp/index.html')
TEMPLATES:
#mysite/myapp/templates/myapp/index.html:
{% load staticfiles %}
<img src="{% static "myapp/image1.jpg" %}" alt="Image 1"/>
In the mysite/settings.py file, I have STATIC_URL = '/static/'. In the folder mysite/myapp/static/myapp, I have a file named image1.jpg.
When I run the development server, it runs fine if I just put some other HTML in my index.html file, but when I try to display the image as above, it just shows a little white box where the image should be. Furthermore, if I go to localhost:8000/myapp/static/myapp/image1.jpg, I get a 404 error.
I'm assuming I'm doing something very obviously wrong...but what is it?
One thing - the STATIC_URL in settings.py is relative to the app directory, not the project directory, right?
Thank you!
When you're running in production, your static files are managed by the server (Apache, nginx) however when your DEBUG is set to true in your settings.py you'll have to tell django to serve the static files for you. To do this add the following to your URLs.py:
from django.conf import settings
(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT}),
This will allow static to be searchable and serve your static files.
img src="{% static 'myapp/image1.jpg' %}" alt="Image 1"/>
Related
I am new to django. I wanted to upload an image but it doesn't show up on website. Instead, it shows a broken image icon. I tried to use load static block but it still doesn't work.
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Website</title>
</head>
<body>
<h1>Hello</h1>
{% load static %}
<img src="{% static 'webdev/static/webdev/images/images.jpg' %}">
</body>
urls.py file:
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
]
views.py file:
from django.shortcuts import render
from django.http import HttpResponse
def home_page(request, *args, **kwargs):
return render(request, 'home.html', {})
file tree: https://i.stack.imgur.com/EYxNI.png
The documentation on Serving static files during development explains how to set up static files. You need to add the views that serve the static files to the urlpatterns:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from homepage import views
urlpatterns = [
path('', views.home_page, name='home'),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
This will serve static files when DEBUG is set to True. In case of production (DEBUG = False), Django does not serve static files. Then you should configure the webserver (nginx/apache/…) to serve the static and media files, or work with a CDN.
Furthermore the path is:
<img src="{% static 'webdev/images/images.jpg' %}">
I dont know why image is not display on the home page. Please see my code. I am on windows running python3 and Django 2.1. Is there any setting need to be done in files somewhere in Django folders like any config file? Please guide
Settting File:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
URL file:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
import jobs.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home', jobs.views.home, name='home'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Model File
from django.db import models
# Create your models here.
class Job(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=300)
Home Page File
<html lang="en">
{% load static %}
<head>
And where I want to show the image is end of a div
<img src="{% static '9.jpg' %}" height="200"></img>
</div>
</section>
In settings.py you will need to add settings for MEDIA_ROOT and MEDIA_URL. That is what the ImageFile upload_to relates to. See the documentation here.
You can then for example reference the image in the home page template as follows:
<img src="{{ '/media/images/9.jpg' }}">
I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
import gallery.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gallery.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Gallery urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^', views.homepage, name = 'home'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Gallery views.py:
def homepage(request):
texts = Sitetext.objects.all()
gal = Galleryimg.objects.all()
gal.order_by('position')
return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal})
And then this is the part of the template code that accesses the image:
{% for g in gallery %}
<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="g.imgfile.url" />
</div>
{% endfor %}
When I create a gallery image, a broken image pops up, but the image is not accessed correctly.
I do this and I am able to serve media files from the Django development server:
urlpatterns += [
url(r'^media/(?P<path>.*)$', django.views.static.serve, {
'document_root': settings.MEDIA_ROOT}),]
It should be enough to include that just in the project urls.py.
The issue with yours could be that your media URL entry in urls.py is not correct. You seem to be not matching the actual URL of the media file, which is probably something like /media/something.png. You seem to be just qualifying on /media/. I also think your regex should be ^media/, not /media/.
Remove the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) part, from your gallery.urls file.
Replace src="g.imgfile.url" with src="{{ g.imgfile.url }}".
Aside question: Why do you pass this big dictionary ({"text1":texts[0].text,...) to your template? It is error prone and bad practice. You should just pass 'texts': texts and inside your template iterate over them with a {% for text in texts %} forloop. So, the render method should be something like render(request, 'index.html', {'texts': texts, 'gallery': gal}).
I'm trying to run my very first project using Python/Django on Openshift and have problem with loading my static files.
I've read the https://docs.djangoproject.com/en/dev/howto/static-files/ multiple times I have been breaking my head over this for a full day but can't figure out the problem.
I'm running a developer server:
python manage.py runserver
setting.py
STATIC_URL = '/static/'
if 'OPENSHIFT_REPO_DIR' in os.environ:
STATIC_ROOT = os.path.join(os.environ.get('OPENSHIFT_REPO_DIR'), 'wsgi', 'static')
else:
STATIC_ROOT = os.path.join(WSGI_DIR, 'static')
template
{% load static %}
<img src="{% static "logo2.png" %}">
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/index/')),
url(r'^index/', include('index.urls')),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += staticfiles_urlpatterns()
The weirdest thing is that after pushing my app to openshift everything is working just fine but on localhost sth goes wrong.
Make long story short:
127.0.0.1:8000/static/logo2.png - Not found
mysite.rhcloud.com/static/logo.png - Yeah, I see the image
I hope it's clear and my problem is as stupid as I imagine.
Django 1.8, OS Windows
SOLUTION:
I've deleted the 'django.contrib.staticfiles' from INSTALLED_APPS and add to the urls.py this peace of code:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Are you in development mode? If yes and if you don't have django.contrib.staticfiles in INSTALLED_APPS, you need to add this to urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Explained here.
I have some issues with "static files" in my project
I'd like to simply load an image.
Here is my code :
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def D3(request):
template = loader.get_template('appli1/D3.html')
context = {}
return HttpResponse(template.render(context, request))
urls.py
from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^D3$', views.D3, name='D3'),
]
D3.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% load staticfiles %}
<img src="{% static "appli1/testimg.png" %}" alt="My image"/>
</body>
</html>
settings.py
STATIC_URL = '/static/'
The image testimg.png is in appli1/static/appli1/
And the file D3.html is in appli1/templates/appli1/
Thanks for your help !
EDIT :
The structure of my project seems good to me, maybe I'm wrong. Here is what it looks like :
test_django/
manage.py
db.sqlite3
test_django/
__init__.py
settings.py
urls.py
wsgi.py
__pycache__/
...
appli1/
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
__pycache__/
...
migrations/
...
static/
appli1/
testimg.png
templates/
appli1/
D3.html
There are following issue with your code:
1) Check quotes in
<img src="{% static "appli1/testimg.png" %}" alt="My image"/>
Technically,in the above "{% static " will be read as one value, then " %}" as other, and finally "My image" as another.
Following is the correct way of doing it:
<img src="{% static 'appli1/testimg.png' %}" alt="My image"/>
This way html read it "{% static 'appli1/testimg.png' %}" as a whole inside which lies 'appli1/testimg.png'.
2) As I don't know your directory structure and hence your root directory, this might be another issue.
If in your 'appli1/static/appli1' your 'static' is at the same level as that of root directory, then it will work fine, which I think is the case as even your templates are in 'appli1/templates/appli1/' and your templates are being loaded. Hence proving that 'static' is at the root level.
Else, if its not the case, and even your templates are not loaded (Coz i'm just assuming your templates are being loaded), then your root 'static' and 'templates' folder are not the same level of root directory and hence the html and static files are not being discovered by the url you are specifying in your html.
One of the issues you might be having is that your STATIC_DIR setting in your project's settings.py file might not be configured. The Django docs have a section on that which is really easy to follow along. After you do that, when you have the {% load static %} tag, when you insert a {% static 'path/to/file.txt' %} tag, Django will look in your projects main static file and then find the app folder and then follow the path you lay out from there. for example, if your file is in an app called 'main' in static/main/images/fart.png, then all you have to do is put scr="{% static static/main/images/fart.png%}"