I have created a model called Product that takes in an ImageField that will be upload on a function I created:
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null= True, blank=True)
def __str__(self):
return self.title
return self.image
def __unicode__(self):
return self.title
I have also created my MEDIA_ROOT and STATIC_ROOT below is code from main urls however I also defined this two on the settings.py:
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So I am able to upload Image from the admin and it uploads properly to the media_root that I created.
When I try calling/displaying the image it render nothing I do not know where I could have made a mistake
{% load static %}
{{ object.title }} <br/>
{{ object.description }} <br/>
{{ object.image.url }}<br/>
<img src="{{ object.image.url }}" class='img-fluid'/>
but the {{ object.image.url }} actually gives me the exact path of the Image which should make sense for the the picture to rendered.
This is the the result output that I was telling about, that I'm getting the image url but I can not display the Image
<img src="/media/{{ object.image }}" alt='xyz'>
Related
Problem:
I cannot get images to appear on my template plant_detail.html. I think I'm calling on variables incorrectly, but not sure what to change.
Context:
I created a model PlantImage, that allows me to associate multiple images within my model Plant.
I then created a class-based view PlantDetailView to link the two models, PlantImage and Plant together.
However, now when I try to display those images in the template plant_detail.html, nothing will appear. How can I get images to appear on my template?
I tried reading through the Django documentation, reading articles, and watching youtube videos, but I'm not sure what I'm missing or need to edit.
My files:
plants/models.py
class Plant(models.Model):
name = models.CharField(max_length=120)
slug = models.SlugField(null=False, unique=True)
description = models.TextField()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("plant_detail", kwargs={"slug": self.slug})
class PlantImage(models.Model):
plant = models.ForeignKey(Plant, default=None, on_delete=models.CASCADE)
images = models.ImageField(upload_to = 'images/')
def __str__(self):
return self.plant.name
plants/views.py
def plant_index(request):
plant_objects = Plant.objects.all()
context = {'plant_objects': plant_objects}
return render(request, 'plants/plant_index.html', context)
class PlantDetailView(DetailView):
model = Plant
template_name = 'plants/plant_detail.html'
slug = 'slug'
def get_context_data(self, **kwargs):
context = super(PlantDetailView, self).get_context_data(**kwargs)
context['plant_images'] = PlantImage.objects.all()
return context
plant_detail = PlantDetailView.as_view()
plants/urls.py
from django.urls import path
from .views import plant_index, plant_detail
app_name = 'plants'
urlpatterns = [
# ex: /plants/
path('', plant_index, name='plant_index'),
# ex: /plants/pothos/
path("<slug:slug>", plant_detail, name="plant_detail"),
]
plants/plant_detail.html
{% block content %}
<body>
<h1> {{ plant.name }} </h1>
<br>
<p> <b>Latin Name: </b>{{ plant.latin_name }} </p>
<br>
<p><b>Description: </b></p>Dj
<p> {{ plant.description }} </p>
<br>
<br>
<p>Images:</p>
<br>
{% for image in plant_images %}
<p><img src="{{ plant.images }}" width="300px"></p>
{% endfor %}
</body>
{% endblock content %}
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('mediafiles'))
Screenshots of output:
The code "PlantImage.objects.all()" gets not only specific image related plant but another images.
so if you want to access PlantImage from Plant, you have to write related_name.
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.related_name
class PlantImage(models.Model):
plant = models.ForeignKey(Plant, default=None, on_delete=models.CASCADE, related_name="plant_images")
...
ImageField inherit FileField. so, you have to know something of Filefield functions.
https://docs.djangoproject.com/en/4.0/ref/models/fields/#filefield-and-fieldfile
if you want to show images, add '.url' like this.
{% for image in plant.plant_images.all %}
<p><img src="{{ image.images.url }}" width="300px"></p>
{% endfor %}
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
I'm trying to get images for an object filtered by the object's id, but for now, I don't even see any request to it in my MySQL database. The snippets of my code are below.
models.py:
class Media(models.Model):
word = models.ForeignKey(Word, on_delete=models.CASCADE)
title = models.TextField(max_length=100, null=True)
image = models.ImageField(upload_to='images/')
views.py:
class MediaListView(generic.ListView):
model = Media
template_name = 'dictionaty_web/index.html'
context_object_name = 'images'
def get_queryset(self):
return Media.objects.filter(word=self.request.resolver_match.kwargs['pk'])
urls.py:
urlpatterns = [
path('languages/<int:pk>/', views.WordMapListView.as_view(), name='wordmaps'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
index.html:
{% for word in words %}
<div class="col-sm text-center">
<div class="card" style="width: 18rem;">
<img scr="{{ MEDIA_URL }}{{ image.image.url }}">
<div class="card-body">
<h5 class="card-title">{{ word.value }}</h5>
</div>
</div>
</div>
{% endfor %}
Your urls.py is also important when serving images in django.
do you have imported in your urls.py the following code
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
path('url/', name_of_view, name = 'url_name'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
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,
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