I am trying to make a blog application, where every post has a featured image. When I upload the image from admin dashboard, I can see the image in my folder. But, when i try to access the url of the image or show the image from source, it's showing nothing.
Here is my code:
models.py
class Post(models.Model):
PRIVACY=(
('0', 'Public'),
('1', 'Private')
)
title = models.CharField(max_length=250)
image = models.ImageField(upload_to="gallery/")
description = models.TextField()
status = models.CharField(max_length=8, choices=PRIVACY, default='0')
tags = TaggableManager()
published = models.DateField(auto_now_add=True)
slug = models.SlugField(max_length=58,blank=True,)
def save(self, *args, **kwargs):
slug_save(self) # call slug_save, listed below
super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('src:post_detail',args=[self.slug])
def get_image(self):
return self.image.url
views.py
def home(request):
posts = Post.objects.order_by('-published')
template = 'home.html'
context = {'posts': posts}
return render(request, template, context)
def post_detail(request,post):
post = get_object_or_404(Post, slug=post)
return render(request,'detail.html',{'post': post})
urls.py
app_name = 'src'
urlpatterns = [
path('', views.home, name='home'),
path('<slug:post>/',views.post_detail,name='post_detail'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
urlpatterns += staticfiles_urlpatterns()
**home.html
{% extends 'base.html' %}
{% block content %}
{% for post in posts %}
<section class="post">
<h3><a class="post-title"
href="{{post.get_absolute_url}}">
{{ post.title }}
</a></h3>
<span class="post-meta">
{{ post.published }}
<a href="{{post.get_image}}">
<img src="{{ post.image.url }}" /></a>
</span>
<p class="post-excerpt">
{{ post.description }}
</p>
</section>
{% endfor %}
{% endblock content %}**
When I try to access some files directly from the image url:
This is the urls.py of my root project :
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('site/', include('src.urls')),
]
This is in my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = 'static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')