我是django的新手,有一个图像问题。当我停留时,当我查看我的博客的主页面与所有文章时,图像一切都很好,但只要我想查看一篇特定的文章,然后由于错误的url/图像开始出现问题
urls.py(project)
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(app)
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
1条答案
按热度按时间inn6fuwd1#
Django使用
STATIC_URL
来确定用于静态文件的url。但是,您的
STATIC_URL
是main/static
,这是一个相对URL。如果您的URL遵循example.com/main/static/file.jpg
模式,则只需使用/
作为前缀