I am getting broken images on django. Below are the relevant information with code, I guess. I am new to django and any information would be greatly appreciated.
name of project/site=imagesite
name of app=gallery
in models.py,
class Photo(models.Model):
pub_date = timezone.now()
image = models.ImageField(upload_to='images')
in views.py,
def view_gallery(request):
photo_list = Photo.objects.all()
return render(request, 'gallery/view_gallery.html', {'photo_list' : photo_list})
in view_gallery.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gallery</title>
</head>
<body>
{% csrf_token %}
{% for photo in photo_list.all %}
<img src="{{ photo.image.url }}" width="240">
<h2> {{ photo.pub_date }} </h2>
<br>
{% endfor %}
</body>
</html>
in settings.py,
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite/media')
in imagesite/urls.py,
urlpatterns = [
path('imagesite/', include('gallery.urls')),
path('admin/', admin.site.urls),
]
in gallery/urls.py,
urlpatterns = [
path('', views.view_gallery, name='view_gallery'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your static() urls should be added to the main urls.py file, not to your gallery/urls.py. Now you're prepending them with /imagesite/ so basically you're telling django to create urls /imagesite/media/ rather than /media/.
Also, just for clarity: This is a url setting that should only be used for development, not for production. So it's better to do like this in your main urls.py:
from django.conf import settings
urlpatterns = [
path('imagesite/', include(gallery.urls)),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Finally, don't assume '/' for paths, as you see you're on Windows, so the path separator is a '\'. Your MEDIA_ROOT setting creates a folder "imagesite/media" rather than a folder "media" inside a folder "imagesite":
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite', 'media')
Related
I'm having issues getting an image to load on my Django web application. I have used the online documentation and tried peoples suggestions that I found on Stackoverflow but I am still not having any luck getting it to load. Here is what I have:
Settings.py:
STATIC_DIR = os.path.join(BASE_DIR,'static')
INSTALLED_APPS = [
...
'django.contrib.staticfiles'
]
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,]
Urls.py:
from django.urls import path
from dir_app import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'dir_app'
urlpatterns=[
path('', views.tradesmen, name='tradesmen'),
path('register', views.register,name='register'),
path('user_login', views.user_login,name='user_login')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Index.html: (Gist)
<!DOCTYPE html>
{% load static %}
<html>
<head>
</head>
<body>
<img src="{% static 'dir_app/tools.png' %}">
</body>
</html>
Here is where the image is stored:
DEBUG should be true if want to use django.conf.url.static
https://github.com/django/django/blob/926148ef019abcac3a9988c78734d9336d69f24e/django/conf/urls/static.py#L23
STATIC_ROOT should be a string, not a list.
https://docs.djangoproject.com/en/3.0/ref/settings/#std:setting-STATIC_ROOT
I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below.
models.py
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractUser
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
profile.html
<!DOCTYPE html>
{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">
</div>
</div>
</body>
{% endblock %}
</html>
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
urls.py(the main urls.py, not of app users)
from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls'), name='index'),
path('profile/', profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
i feel stupid for not seeing this :| had to add this.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use this in your urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {'document_root':
settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve, {'document_root':
settings.STATIC_ROOT}),
]
And in your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
I am trying to use static images in my template using the DJANGO framework, but the images don't display on my page.
I have followed the manuals completely.
Does anyone have any ideas?
Here the code :
html :
{% load staticfiles %}
div class="portfolio-item">
<img class="img-portfolio img-responsive" src="{% static portfolio2.jpg %}">
</div>
settings.py :
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'static','static_dirs'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media')
MEDIA_URL = ('/media/')
urls.py
+
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Try: quotes 'portfolio2.jpg' before file
<img class="img-portfolio img-responsive" src="{% static 'portfolio2.jpg' %}">
Image uploaded by user is not displaying though i have not done wrong in template. Also i have defined MEDIA_URL and MEDIA_ROOT. What might be the reason for not getting image displayed?
Code
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
project/urls.py(urls.py of main project)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
templates/shop/product/list.html
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/no_image.png' %} {% endif %}" >
</a>
I know this question is asked multiple times but my code took after the documentation and still i could not display image. Could anyone help me, please?
It is working now after fresh restart of the server. So the above code and process of serving media files is correct.
I have configured my static settings like so:
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('js', os.path.join(STATIC_ROOT, 'js')),
('css', os.path.join(STATIC_ROOT, 'css')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
and these in my urls.py:
urlpatterns = patterns('',
url(r'^login/?$', login, name='login'),
url(r'^logout/?$', logout_then_login, name='logout'),
url(r'^profile/(?P<user_id>\d+)$', 'profiles.views.detail'),
url(r'^profile/edit$', 'profiles.views.edit'),
)
urlpatterns += staticfiles_urlpatterns()
It works very well for the url localhost:8000/login, but when I get to the localhost:8000/profile/edit site, which is handled by my profiles App, the {{ STATIC_URL }} changes all the paths from /static/... to /profile/static/..., so my javascripts and stylesheets are not found any more.
What'd I do wrong?
EDIT: Here would be my base.html
<!DOCTYPE html>
<html>
<head>
<title>Neighr{% block title %}{% endblock %}</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.min.js"></script>
{% block script %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Since you're using the django built-in developement server, try to remove the following line from your urls.py:
urlpatterns += staticfiles_urlpatterns()
In production, you'de better not serve static files with django, so use the collectstatic command.
edit
If settings.py, try something like this:
STATIC_ROOT = os.path.join(os.path.dirname(__file__), '../../static')
STATIC_URL = '/static/'