Reputation: 29
I want to display images on my Django template file but the images are broken. All the images are uploaded in media static files but they cannot be displayed in my template file, when I go to Django admin page and click on the image link, here is the error message I got: Page not found(404)
Can anyone please help me with this issue? Thanks in advance.
Here is the template file "post_detail.html":
<div class="row">
<div class="col-6">
{% if instance.image %}
<img src="{{ instance.image.url }}" alt="image" class="img-thumbnail">
{% endif %}
<div class="post-detail-item text-justify"><p> {{ instance.get_markdown }} </p> </div>
</div>
</div>
Here is my app => posts views.py:
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type= content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"comments": comments,
"comment_form":form,
}
return render(request, "post_detail.html", context)
Here is my app => posts urls.py:
from django.contrib import admin
from django.urls import path, re_path
from .views import (post_list,
post_create,
post_detail,
post_update,
post_delete,
) urlpatterns = [
path('', post_list, name='list'),
path('create/', post_create),
re_path('(?P<slug>[\w-]+)/edit/', post_update, name='update'),
re_path('(?P<slug>[\w-]+)/delete/', post_delete),
re_path('(?P<slug>[\w-]+)/', post_detail, name='detail'), ]
Here are posts models.py and upload_location :
def upload_location(instance, filename):
PostModel = instance.__class__
new_id = PostModel.objects.order_by("id").last().id + 1
return "%s/%s" %(new_id, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
title = models.CharField(max_length=40, null=False)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
read_time = models.IntegerField(default=0)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
Here are my settings.py and the main_app urls.py:
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn")
main_app urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('comments/', include(('comments.urls', 'comments'), namespace='comments')),
path('register/', register_view, name='register'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('', include(('posts.urls', 'posts'), namespace='posts')),]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upvotes: 0
Views: 1262
Reputation: 6616
Uploaded files aren't served in development by default.
Add this on to the end of your URL patterms:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
However, this isn't suitable for production, so you will need some other method when you get to that stage (serving from nginx or a CDN or whatever).
Upvotes: 1