django 404错误提示:图片未显示

os8fio9y  于 2023-02-10  发布在  Go
关注(0)|答案(2)|浏览(127)

我按照官方django文档的图像字段。我可以存储图像在数据库中,但当我试图在浏览器中显示它时,我得到404错误。
我的设置文件,

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.core.context_processors.static',
            ],
        },
    },
]

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static")
MEDIA_ROOT =  os.path.join(os.path.dirname(BASE_DIR),"media")
MEDIA_URL = '/media/'

我的models.py文件

class Add_prod(models.Model):
    book = models.CharField("Book Name",max_length=40)
    image = models.ImageField(upload_to='static/images',null=True)

我的views.py文件

def add_prod(request):
    form = ProdForm(request.POST or None,request.FILES or None)
    my_products = Add_prod.objects.all()
    context = {
            "form":form,
            "products":my_products
    }
    if form.is_valid():
        instance = form.save(commit=False)
        book = form.cleaned_data.get("book")
        image = form.cleaned_data.get("image")
        instance.book = book
        instance.image = image
        instance.save()
   return render(request,"add-prod.html",context)

www.example.com文件的一小部分urls.py,

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_URL)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_URL)

我的模板文件的一小部分,

{% for i in products %}  
            <tr>
                <td>{{i.book}}</td>
                <td><img src="{{ MEDIA_URL }}{{i.image.url}}" alt="No Image"></td>
            </tr>
{% endfor %}

这是Eclipse控制台中的错误,

Not Found: /media//media/static/images/644.jpg
"GET /media//media/static/images/644.jpg HTTP/1.1" 404 1800
icnyk63a

icnyk63a1#

urls.py中,我注意到它必须是:

static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

kq0g1dla

kq0g1dla2#

将下面的代码添加到**”urls.py“(与”settings.py“**相同的目录),然后,您的错误将得到解决:

from django.conf.urls.static import static
from django.conf import settings

...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

相关问题