我是 django 的新手,我遇到了图像问题。当我查看我博客的主页和所有文章时,图片一切正常,但是当我想查看一篇特定文章时,由于错误的 url/
,图像开始出现问题urls.py(项目)
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py
from django.shortcuts import render
from .models import *
def index(request):
posts = Post.objects.all()
topics = Topic.objects.all()
return render(request, "index.html", {"posts": posts, "topics": topics})
def post(request, postinf):
post = Post.objects.get(title=postinf)
return render(request, "post.html", {"post": post} )
urls.py(应用程序)
from django.urls import path
from . import views
urlpatterns = [
path('blog', views.index),
path('blog/<str:postinf>/', views.post, name="postdetail"),
]
settings.py
STATICFILES_DIRS = [
BASE_DIR / "main/static/",
]
STATIC_URL = 'main/static/'
models.py
from django.db import models
from django.contrib.auth.models import User
class Topic(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
user_avatar = models.ImageField(null=True, blank=True, upload_to="main/static/images")
def __str__(self):
return str(self.user)
class Post(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=20, verbose_name="Название поста")
post_text = models.TextField(max_length=500)
topic = models.ForeignKey(Topic, on_delete = models.DO_NOTHING)
time = models.DateField(auto_now=True)
post_image = models.ImageField(null=True, blank=True, upload_to="main/static/images")
def __str__(self):
return self.title
+主页(http://127.0.0.1:8000/blog)有图片没问题
- 当我去 http://127.0.0.1:8000/blog/post/ 在控制台上得到这个错误并且没有图像
Not Found: /blog/post/main/static/images/istockphoto-10252.jpg
[19/Apr/2023 01:28:00] "GET /blog/post/main/static/images/istockphoto-10252.jpg HTTP/1.1" 404 2699
Django 使用
STATIC_URL
来确定用于静态文件的 url。
但是您的
STATIC_URL
是main/static
,这是一个相对URL。如果您的 URL 遵循 /
模式,则只需要以
example.com/main/static/file.jpg
为前缀
# In settings.py
STATIC_URL = '/main/static/'