无法在Djang中加载静态文件

2024-06-26 14:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加一个图像到一个非常基本的html模板。我能够呈现html文件,但不幸的是图像将不会显示。你知道吗

这是我的错误:

Not Found: /exapp/pic.jpg
[21/Apr/2018 18:43:49] "GET /exapp/pic.jpg HTTP/1.1" 404 2145

我注意到django正在查找路径为/exapp的文件/图.jpg,所以我在静态目录中创建了一个名为exapp的文件夹,并将图像放在其中。仍然没有图像:(

文件结构如下:

    ─ db.sqlite3
├── exapp
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-35.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-35.pyc
│   │   ├── __init__.cpython-35.pyc
│   │   ├── models.cpython-35.pyc
│   │   ├── urls.cpython-35.pyc
│   │   └── views.cpython-35.pyc
│   ├── static
│   │   └── exapp
│   │       └── pic.jpg
│   ├── templates
│   │   └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
└── mysite
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   ├── settings.cpython-35.pyc
    │   ├── urls.cpython-35.pyc
    │   └── wsgi.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

下面是有问题的HTML文件:

    <html>
    <head> 
        <title> Hello world</title>
    </head>

    <body>
        Look it worked 
    {% load static %}
    <img src="pic.jpg" alt="Smiley face" height="200" width="420">
    </body>

</html>

以下是设置文件:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'tie19%e+ri*g3#54b)axh&!8rentwx)xnsjbk&kx09(10le%7a'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'exapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

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

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

以下是我的视图和URL文件:

 ---------url.py in mysite folder------------
    from django.contrib import admin
    from django.urls import path, include

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('exapp/',include('exapp.urls')),
    ]
    -----------urls.py in exapp folder--------------
    from django.urls import path


    from . import views 

    urlpatterns = [
        path('', views.index, name='index'),
    ]

 ----------Views in exapp folder--------------------------
    from django.shortcuts import render

    # Create your views here.
    from django.http import HttpResponse


    def index(request):
        return render(request,'index.html')

因此,作为一个概述,HTML模板确实呈现给页面。但我由于某种原因无法弄清楚如何将图像链接在html代码中显示到屏幕上。一切似乎都在正确的地方。谢谢你的帮助!你知道吗


Tags: 文件pathdjangopyimportauthadmininit
1条回答
网友
1楼 · 发布于 2024-06-26 14:13:55

您应该尝试更改图像源。你知道吗

这就是你所拥有的:

<img src="pic.jpg" alt="Smiley face" height="200" width="420">

试试这个:

<img src="{% static "exapp/pic.jpg" %}" alt="Smiley face" height="200" width="420">

这对我有用!你知道吗

祝你好运!你知道吗

相关问题 更多 >