Django media files not loading - python

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/'

Related

Django: Static Image Not Loading

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

Broken Images on Django

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')

Not able to render ImageField of a model in Django Templets [duplicate]

See my GitHub
https://github.com/rg3915/gallery
How to render images on Django template?
But he is returning:
Gallery
media/3665_1280x800_8UX8tgG.jpg
Tour de France
media/281405_fSRBDZu.jpg
bike of children
How to render the images?
Does the bug is in settings.py
urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from gallery.core.views import *
from django.contrib import admin
urlpatterns = patterns(
'gallery.core.views',
url(r'^$', 'home', name='home'),
url(r'^gallery/$', GalleryList.as_view(), name='gallery_list'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = BASE_DIR.child('media')
MEDIA_URL = '/media/'
STATIC_ROOT = BASE_DIR.child('staticfiles')
STATIC_URL = '/static/'
gallery_list.html
<html>
<body>
<h1>Gallery</h1>
{% if gallery %}
{% for photo in gallery %}
<p><img src="{{ photo.photo.url }}" width="300px"></p>
<p>{{ photo.description }}</p>
{% endfor %}
{% endif %}
</body>
</html>
The secret is photo.photo.url

Django Display ImageField With Media Dir

I am using Django 1.9.3. I am trying to display media files uploaded by say a user (e.g. imageFields).
HTML Page:
{% for project in projects %}
<img src="{{ project.image.url }}" class="img-responsive" alt="">
{% endfor %}
Views.py:
def home(request):
projects = AvailableProject.objects.all().order_by('-published_date')
return render(request, 'accounts/home.html', {'projects': projects})
urls.py:
urlpatterns = [
...
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
('global', os.path.join(BASE_DIR, 'smilesite', 'project_static')),
('admins', os.path.join(BASE_DIR, 'admins', 'static')),
('accounts', os.path.join(BASE_DIR, 'accounts', 'static')),
('mysite', os.path.join(BASE_DIR, 'mysite', 'static')),
('media', os.path.join(BASE_DIR, 'media')),
)
# print(STATICFILES_DIRS)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
# Define place to save media (e.g. pictures for all the projects)
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py:
from django.db import models
from django.conf import settings
# Create your models here.
class AvailableProject(models.Model):
image = models.ImageField(upload_to=settings.MEDIA_ROOT)
I have literally went through every single stack over flow page on this and tried the following solutions, but still has not worked...:
<img src="{% static 'media/{{project.image.title}}.jpg' %}" class="img-responsive" alt="">
<img src="{{ project.image.url }}" class="img-responsive" alt="">
I don't know why the project.image.url is not showing the corresponding image correctly.
The reason was exactly what Joni Bekenstein said.
I changed this one line and everything worked:
image = models.ImageField(upload_to='uploads/')
Then {{ project.image.url }}, was the correct url.

Python Django (static files/change ip server)

I have one problem. When i change ip adress for server, then my css (Bootstrap) don't work.
urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', 'Blog.views.my_blog')
)
if settings.DEBUG == True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
base.html
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="ru">
<title> Savichev's site </title>
<!-- Bootstrap -->
<link rel="stylesheet" href={% static "css/bootstrap.css" %}>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset="UTF-8">
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
What's wrong ?
CSS work correctly only on ip 127.0.0.1:8000
I suppose, with the little information you gave us, you need to provide a STATIC_ROOT variable in your settings.py.

Categories