Issue
I have a Django model for coaching programs in my site, I want to be able to upload a thumbnail image for every program. I used FileField() for that and set the "upload_to=" to the static folder. I am trying to display the image in the site using django templates, I configured the 'scr' attribute in the tag but I am getting a 404 on GET response when the HTML tries to get the image:
[01/Jan/2024 21:13:00] "GET /fit/static/fit/coaching/program_imgs/article_img.jpg HTTP/1.1" 404 3818
I just want to be able to display the images uploaded to the db in the site. When I acess the folder that the image was uploaded, the image is there just like it should be, I don't know why I can't display it in the HTML.
Important note: I am creating the db objects for the articles directly via the django admin site.
here is my models.py:
class coaching_programs(models.Model):
coach = models.ForeignKey(User,on_delete=models.CASCADE, related_name='coach')
title = models.CharField(max_length=35, unique=True)
description = models.CharField(max_length=120)
price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
text = models.FileField(upload_to='fit/static/fit/coaching/program_text/',null=True,blank=True)
# i will put md files in this filefield() above.
img = models.FileField(upload_to='static/fit/coaching/program_imgs/',null=True,blank=True)
my HTML/ django templates:
{%for post in posts%}
<div class="post">
{{post.img}}
<img src="../../../{{post.img}}" alt="">
<p>{{post.title}}</p>
<p>{{post.price}}</p>
<p>{{post.description}}</p>
</div>
{%endfor%}
views.py:
def coaching(request):
return render(request,"fit/coaching.html",{
'posts':coaching_programs.objects.all(),
})
I'm sorry if there is any english errors in this, I'm brazillian and a begginner using Django, so any feedback is very aprecciated!
Solution
first of all when you want to upload media to your server you must configure the server to tell it where to save the files
add in settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
in url.py adds
from django.conf.urls.static import static
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then in models.py
class coaching_programs(models.Model):
...
text = models.FileField(upload_to='fit/coaching/program_text/',null=True,blank=True)
img = models.FileField(upload_to='fit/coaching/program_imgs/',null=True,blank=True)
# the downloaded files will have as root the MEDIA_ROOT configured in settings.py
finally in django templates
{%for post in posts%}
...
<img src="{{post.img.url}}" alt="">
...
{%endfor%}
Answered By - Wilfried-Tech
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.