Django does not see the static files images - django

I'm trying to create an online store with Django. I want to add photos of goods, but Django for some reason does not see them. Please help to solve the problem.
Here is a screenshot of error:
here is settings.py
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
'../static/products/media/product_images/',
)
models.py
from django.db import models
# Create your models here.
class Product(models.Model):
name = models.CharField(max_length=70, blank=True, null=True, default=None)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
description = models.TextField(blank=True, null=True, default=None)
short_description = models.TextField(blank=True, null=True, default=None)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s, %s" % (self.price ,self.name)
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
class ProductImage(models.Model):
product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='static/media/product_images/')
is_active = models.BooleanField(default=False)
is_main = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s" % self.id
class Meta:
verbose_name = 'Фотография'
verbose_name_plural = 'Фотографии'
main urls.py file
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('online_shop.urls', namespace='online_shop')),
path('', include('products.urls', namespace='products')),
path('', include('orders.urls', namespace='orders')),
]
html template
{% extends 'online_shop/base.html' %}
{% load static %}
{% block content %}
<section>
<div class="top-section">
<img src="{% static 'img/clem.png' %}" class="img-fluid">
</div>
</section>
<section>
<div class="container">
<div class="row">
{% for product_image in product_images %}
<div class="col-lg-3">
<div class="product-item">
<div>
<img src="{{product_image.image}}" alt="" class="img-fluid">
</div>
<h4>{{product_image.product.name}}</h4>
<p>{{product_image.product.description|truncatechars_html:80 }}</p>
<div class="price">
{{product_image.product.price}} ГРН
</div>
<div class="add-to-card">
<button class="btn btn-success">
Добавить в корзину
</button>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</section>
{% endblock content %}

You may need to do some modifications
settings.py
# prefix used in static files path rendering
STATIC_URL = '/static/'
# store static files once execute python manage.py collectstatic
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
# directories where static files are stored in the development environment
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# prefix used upon uploaded images
MEDIA_URL = '/media/'
# where uploaded images should save
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
# lets you have the ability to view images even in development environment
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
update:
Since you use static/media/product_images/ as upload path, the uploaded files will be saved in
project-root-dir/media/static/products/media/product_images
Hope this helps!

you can do this by adding the following snippet to your urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('online_shop.urls', namespace='online_shop')),
path('', include('products.urls', namespace='products')),
path('', include('orders.urls', namespace='orders')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Related

django image uploaded section doesnot shows up in production

I tried to upload image from the admin side in production but it doesn't shows up or stores in static/images but it used to work while working in local.
However my static images are loaded and also those I've saved in development are also showing up but while adding new images it doesn't get added to static files.
My model:
class Gallery(models.Model):
title = models.CharField(max_length=150)
image = models.ImageField(upload_to='images/',null=True,default="avatar.svg")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls'))
]
urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Gallery .html
{% for gallery in gallerys %}
<!-- ITEM 1 -->
<div class="col-xs-6 col-md-3">
<div class="box-gallery">
<a href="{{gallery.image.url}}" title="Gallery #1">
<img src="{{gallery.image.url}}" alt="" class="img-fluid" />
<div class="project-info">
<div class="project-icon">
<span class="fa fa-search"></span>
</div>
</div>
</a>
</div>
</div>
{% endfor %}
Settings.py
here i've uploaded only the required ones
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'base.NewUser'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static/")
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "/static/images")
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
views.py
def gallery(request):
gallerys = Gallery.objects.all()
context = {'gallerys':gallerys}
return render(request, 'base/gallery.html',context)
am i missing something here?
Thanks in advance
The way to store images in static folder.
Do this:
views.py:
def gallery(request):
if request.method == 'POST':
form = YourForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['image'])
model_instance = form.save()
model_instance.save()
else:
form = YourForm()
gallerys = Gallery.objects.all()
context = {'gallerys':gallerys}
return render(request, 'base/gallery.html',context)
def handle_uploaded_file(f):
with open('static/images/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
settings.py:
STATIC_URL = 'static/'
STATIC_ROOT=os.path.join(BASE_DIR,'static')
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
This is the way that you can store static files.
I hope this may be get you

Django not show image field

Not showing image on upload, what is the problem?
setting.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
html.
{% for tt in article %}
<div class="content_box">
<div class="content_l left">
<div class="horoscope_box_big">
<div class="blog_img1">
<img src="{{ tt.image.url }}" alt="{{tt.title}}" width="50%" /> {{ tt.image.url }}
</div>
<h1 class="blog_title1"> {{ tt.Title }}
<div class="blog_descr1"><h1>more about</h1>
<p> {{ tt.body }}</p>
</div>
</div>
{% endfor %}
models.py
class Blogmodel(models.Model):
Title = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to="images/",null=True)
body = RichTextField(blank=True, null=True)
slug = AutoSlugField(populate_from='Title', unique=True,blank=True, null=True)
def __str__(self):
return self.Title
views.py
def blog_list(request):
articles = Blogmodel.objects.all()
args = {'articles':articles}
return render(request,'blog.html',args)
def blogDetail(request, slug):
article = Blogmodel.objects.filter(slug=slug)
args = {'article':article}
return render(request,'blogdetail.html',args)
urls.py
from django.urls import path
from .views import singCategory,Home,blog_list,blogDetail
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',Home,name= "Home"),
path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'),
path("blog/",blog_list, name="blog_list"),
path("blog/<slug:slug>",blogDetail, name="blogDetail"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your settings.py:
MEDIA_URL = '/media/'
Your template:
<img src="{{ article.image.url }}">
check if you have Pillow installed, pip install pillow,

ValueError: The 'cover' attribute has no file associated with it

I uploaded image from admin panel and it get stored in media/img.I want to display posted image in my index.html but i get this ValueError: The 'cover' attribute has no file associated with it.I think I am making mistake in url or view ..I am new to django.
# app urls.py
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
]
# project urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("blog.urls"), name="blog-urls"),
path("summernote/", include("django_summernote.urls")),
]
# views.py
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
paginate_by = 3
# models.py
class Post(models.Model):
cover = models.ImageField(upload_to='image/', default='')
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="blog_posts"
)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
<!-- index.html -->
<img src={{ post.cover.url }} alt="{{ post.title }}" width="160px" height="220px">
List view output is a queryset, means a list of instances, so you have to loop through it.
{% for post in object_list %}{% if post.cover %}
<img src={{ post.cover.url }} alt="{{ post.title }}" width="160px" height="220px">{% endif %}
{% endfor %}
also change the include url to
path("", include("blog.urls"))
without name, if you want you can add a namespace

How to serve media files with Django in local environment?

I have a problem when trying to display in a template a picture from my media file (for example a profil picture from an user). I have already looked at many topics, and everytime the answer is simply adding the line urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the urls.py file. But I already have it and it still doesn't work. Here are the relevant part of my files :
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('actualites.urls')),
path('inscription/', include('inscription.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
views.py
def home(request):
return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()})
models.py
class Plat(models.Model):
titre = models.CharField(max_length = 100)
date = models.DateField(default=timezone.now, verbose_name="Date de préparation")
photo = models.ImageField(upload_to = "photos_plat/", blank = True)
class Meta:
verbose_name = "Plat"
ordering = ['date']
def __str__(self):
return self.titre
You can see that the pictures are recorded in the photos_plat directory, which is a subdirectory of the media directory.
the template :
{% extends "base.html" %}
{% block content %}
<h2>Bienvenue !</h2>
<p>
Voici la liste des plats disponibles :
</p>
{% for meal in last_meals %}
<div class="meal">
<h3>{{ meal.title }}</h3>
<img src="{{ meal.photo.url }}" height=512 width=512/>
<p>{{ meal.description|truncatewords_html:10 }}</p>
<p>Afficher le plat</p>
</div>
{% empty %}
<p>Aucun plat disponible.</p>
{% endfor %}
{% endblock %}
When I go the home page, I get the following error : ValueError at /
The 'photo' attribute has no file associated with it.
I have tried moving the pictures from the "photos_plat" directory directly to the media directory but that changes nothing.
I don't know what I did wrong, can someone help me please ?
Thanks in advance !

Django media image not displaying

I am developing a django app were i am uploading images through the admin panel
i have implemented this in my other apps but i can seem to get what is wrong with my configurations as follows
settings.py
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'ntakibariapp.Member'
LOGOUT_REDIRECT_URL = 'ntakimbari:_login'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('ntakibariapp.urls')),
path('accounts/', include('django.contrib.auth.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, ducument_root=settings.MEDIA_ROOT)
models.py
class Community_work(models.Model):
where = models.CharField(max_length=80)
time = models.TimeField(blank=False)
date = models.DateField(blank=False)
image_of_area = models.ImageField(upload_to='photos',blank=True)
post_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.where
template/communtity_work.html
{% extends 'temp/base.html' %}
{% block title %}community works{% endblock %}
{% block body %}
<div class="container">
{% for work in works %}
<p>Picture of the area <img src="{{work.image_of_area.url}}"></p>
<p>Where: {{work.where}}</p>
<p>Time: {{work.time}}</p>
<p>Date: {{work.date}}</p>
{% endfor %}
</div>
{% endblock %}
in urls.py you have a misspell try use
document_root
instead of ducument_root
Also shouldn't the tag be <img src="{{community_work.image_of_area.url}}">?