我想在Django模板文件上显示图像,但是图像坏了。所有图像都上传到媒体静态文件中,但是当我转到Django管理页面并单击图像链接时,它们无法显示在我的模板文件中,这是我收到的错误消息: Page not found(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>
这是我的应用程序=>发布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)
下面是我的应用程序=>帖子的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'), ]
这是帖子model.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)
答案 0 :(得分:0)
默认情况下,上传的文件不在开发中。
将其添加到您的URL模式末尾:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
但是,这不适合用于生产,因此,进入该阶段时,您将需要其他方法(通过nginx或CDN或其他方法提供)。