ValueError: The 'image' attribute has no file associated with it - django

is there something wrong with my code? i already run makemigrations and migrate, and i can see the picture i saved on the admin site, but why when i try to call this picture on my html i received this error?
this is my html
{% for perfume in s %}
<img src="{{perfume.image.url}}" width="192px" height="192px" class="class">
{% endfor %}
my views.py
s = Perfume.objects.all()
....
my models.py
class Perfume(models.Model):
image = models.ImageField(upload_to='image',null=True, blank=True)
....
my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGIN_REDIRECT_URL = '/'
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
def get_success_url(self, request, user):
return (get_success_url)
my urls.py
urlpatterns = [
....
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Your ImageField declared blank=True, null=True so image can be empty. You need to check if image has uploaded in your html.
{% for perfume in s %}
{% if perfume.image %}
<img src="{{ perfume.image.url }}">
{% endif %}
{% endfor %}

Related

Problem is that image is not saving . when i am select image and upload all code working properly but image does not save django

Problem is that image is not saving. when I am select an image and upload all the code working properly but the image does not save. I checked all the code line by line I do not understand what's the problem. I also see the media file any image is saved or not, but the image wasn't saved.
this is models.py in this file I use the image field
models.py
class Answer (models.Model):
question=models.ForeignKey(Question,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE, null=True)
img=models.ImageField(null=True,blank=True,upload_to='Answer_Img')
detail=RichTextUploadingField()
add_time=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.detail
forms.py
class AnswerForm(ModelForm):
class Meta:
model=Answer
fields=('detail','img')
labels={'img':'Upload Image'}
views.py
def answer(request,pk,slug):
try:
trend=Question.objects.get(pk=pk,slug=slug)
except:
raise Http404("Post Does Not Exist")
tags=trend.tags.split(',')
ans=Answer.objects.filter(question=trend)
answerform=AnswerForm
if request.method=='POST':
answerData=AnswerForm(request.POST)
if answerData.is_valid():
answer=answerData.save(commit=False)
answer.question=trend
answer.user=request.user
answer.save()
p=messages.success(request,'Answer has been submitted.')
return HttpResponseRedirect(trend.slug)
return render(request,"ask/answer.html" ,{
'trends':trend,
'tags':tags,
'answer':ans,
'form':answerform,
})
answer.html
{% if user.is_authenticated %}
<div class="container">
<div class="py-5 text-center bg-secondary text-white">
<h1 class="mb-3">Upload Image</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<input type="submit" class="btn btn-danger" value="Upload">
</form>
</div>
{% else %}
<h3><P>Sign In/Sign Up before posting answers</P></h3>
<h4><li>Sign In</li><h4>
<h4> <li>Sign Up</li><h4>
{% endif %}
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
# my url patterns here
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Use request.files to get the img. please check if the media folder is in your base directory and the subfolder is named correctly.
if request.method == "POST":
answer_form = Answer_form(data=request.POST)
if(answer_form.is_valid()):
ans = answer_form.save(commit=False)
#ans.user = user
if 'img' in request.FILES:
ans.img = request.FILES['img']
ans.save()
else:
print(answer_form.errors)
Here is the documentation page :
File Uploads

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 !

Can't display images django

How can I display images from django models on tis page datat.ru/shop ?
I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" />
But only http://datat.ru/static/media/images/2.png returns image
How can I convert src="{{ shop.cover.url }}" to static/media/images/ ???
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('shop/', views.shop_list, name='shop'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
class Company(models.Model):
title = models.TextField()
cover = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
shop_list.html
{% extends 'blog/base.html' %}
{% load staticfiles%}
{% block content %}
{% for shop in shops %}
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" />
</div>
</div>
{% endfor %}
<!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> -->
{% endblock %}
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
and this to urls
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

django: Images are not loading

I need to show images in templates. The images are fetched from models. My models.py reside in an app named services:
class Car_model(models.Model):
name = models.CharField (max_length = 25, blank=False)
...
category = models.ForeignKey (Category, on_delete=models.CASCADE)
photo = models.ImageField (upload_to ='static/images/models')
I have added these lines in my settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'media') # i added it later
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
I have also added this line in my project_name's urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I am trying to get the images in my templates through this code:
{% load static %}
{% for c in ca %}
<p><strong>{{ c.car_no }}</strong>--<em>{{ c.car_model }}</em>--{{ c.garage }}</p>
<img src="{{ c.car_model.photo.url }}" height="200" />
<form action="{%url 'booking' c.id c.garage.id %}" method="POST">
{% csrf_token %}
<input type="submit" name="the_selected_car" value="Select this car">
</form>
{% endfor %}
But whatever I try photos aren't showing. I tried by placing this:
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in my services app's urls.py but that didn't help.
You forget to add MEDIA_ROOT and MEDIA_URL in settings.py and load media urls in urls.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and in urls.py
urlpatterns = [
........
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your could Refactor your upload_to in photo field
1. If you want to upload images in static director
photo = models.ImageField (upload_to ='static/images/models')
And set static folder in MEDIA_ROOT as below
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
2. If you want to upload images in media director
Since your are storing uploaded images I would suggest store in defferent director like media , uploads
Change your field as below.
photo = models.ImageField (upload_to ='media/images/car_model')
Now All your images related to Car_Model will be saved inside media/images/car_model
And set media folder in MEDIA_ROOT as below MEDIA_ROOT as below
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
you didn't include MEDIA Urls in your urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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}}">?