获取django.contrib.staticfiles.views.serve引发的异常

时间:2019-04-07 12:02:40

标签: django

我在Django中很幼稚。在这里尝试一些东西。我正在使用静态文件,并且被卡在这里。请在这里帮助我。

我对static_root和static_dirs非常困惑。我正在关注一个在线教程,其中未使用静态根目录,并且他们的项目运行正常。如果要尝试的话,我会遇到很多错误和异常。

这是我的观点:

from django.shortcuts import render
from django.http import HttpResponse



def index(request):
    my_dict={'insert_me':"Hello I am from views.py"}
    return render(request,'first_app/index.html',context=my_dict)

这是我的项目网址:

from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from first_app import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns


urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^first_app/',include('first_app.urls')),
    url(r'^admin/', admin.site.urls),]

urlpatterns += staticfiles_urlpatterns()

这是我的应用程序网址:

from django.conf.urls import url
from first_app import views
from django.contrib import admin

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

index.html:

{% load staticfiles%} 
<html> 
    <head> 
        <meta charset="utf-8"> 
        <title>DJ Page</title> 
    </head> 
    <body> 
        <h1>Hello this is index.html!</h1> 
        <img src="{% static 'images/dj.jpg'%}" alt='oh oh! did not show'> 
    </body> 
</html>

这是我的设置:

“”“

Django settings for Twenty3rdMrach project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

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__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
#TEMPLATES_DIR=os.path.join(TEMPLATES_DIR,'first_app')
print(TEMPLATES_DIR)
STATIC_DIR=os.path.join(BASE_DIR,'static')
print (STATIC_DIR   )



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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mz^^exko@!2czk35u$w-qr&v8u(46(fp7#u41ctabvwf=mz9m&'

# 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',
    'first_app',
]

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 = 'Twenty3rdMrach.urls'

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'udemy1',
        'USER':'root',
        'PASSWORD':'Ravi@go123',
        'HOST':'localhost',
        'PORT':'3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/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.1/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.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static/'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media/')

同时点击网址:

http://127.0.0.1:8000/static/images/dj.jpg

am遇到以下错误:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/static/images/dj.jpg
Raised by:  django.contrib.staticfiles.views.serve
'images\dj.jpg' could not be found

您看到此错误,因为Django设置文件中的DEBUG = True。将其更改为False,Django将显示标准的404页面。

2 个答案:

答案 0 :(得分:0)

我认为您应该删除STATICFILES_DIRSTATIC_ROOT中的结尾斜杠

STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media')

答案 1 :(得分:0)

STATICFILES_DIR -设置是告诉Django要扫描哪些目录的静态文件。

STATIC_ROOT -设置是告诉Django在执行python manage.py collectstatic命令时将所有静态文件放在哪里。