You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django非首页加载静态图片路径异常,自动添加页面URL前缀

Django静态文件服务问题:详情页图片加载404

图片存储于project/static/images目录,首页加载图片正常,但在contact_details页面加载时出现404错误,请求路径为:

"GET /contact_details/static/images/contact_image.png HTTP/1.1" 404 4212

可见Django自动将页面路径contact_details添加到了图片路径前。

项目相关代码

settings.py

BASE_DIR = Path(__file__).resolve().parent.parent

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR,'accounts'],
        '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',
            ],
        },
    },
]

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_URL = '/images/'

MEDIA_ROOT = BASE_DIR / 'images'

urls.py

urlpatterns = [
    path('', views.home, name="home"),
    path('contact_details/', views.contactDetails, name="contact_details"),
]

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

views.py

def contactDetails(request, pk):
    contact = Contact.objects.get(id=pk)
    image = Image.objects.get(id=contact.image_id)

    form = ContactForm(instance=contact)
    if request.method == 'POST':
        form = ContactForm(request.POST, request.FILES, instance=contact)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('contact_image', args=(pk,)))

    context = {'contact': contact, 'image': image, 'form': form}

    return render(request, 'accounts/contact_details.html', context)

contact_details.html

{% load static %}

<img src="{{ image.path }}" class="img-fluid">

此前尝试调整STATIC_URL开头的斜杠,未解决问题。

问题解决:两处关键修改

修改后的settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_URL = '/images/'

MEDIA_ROOT = BASE_DIR

修改后的contact_details.html

{% load static %}

<img src="{{ image.path.url }}" class="img-fluid">

内容的提问来源于stack exchange,提问作者Daze8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:23:26