Я хочу отображать изображения в моем файле шаблона Django, но изображения повреждены.Все изображения загружаются в медиа-статические файлы, но они не могут быть отображены в моем файле шаблона, когда я захожу на страницу администрирования Django и нажимаю ссылку на изображение, вот сообщение об ошибке, которое я получил: Страница не найдена (404)
Может кто-нибудь помочь мне с этим вопросом?Заранее спасибо.
Вот файл шаблона "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>
Вот мое приложение => 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)
Вот мое приложение=> 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'), ]
Здесь находятся записи models.py и 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)
Вот мои settings.py и 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)