Python pycharm与django教程中的导入问题
昨天,我开始通过本教程学习django: 但是我在这里得到一个Python pycharm与django教程中的导入问题,python,django,pycharm,Python,Django,Pycharm,昨天,我开始通过本教程学习django: 但是我在这里得到一个导入错误: 文件:django_1/src/dj30/url.py from django.contrib import admin from django.urls import path from posts.views import post_list_view # ERROR LINE urlpatterns = [ path('admin/', admin.site.urls), path('posts
导入错误
:
文件:django_1/src/dj30/url.py
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view # ERROR LINE
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
这是我的目录树:
我假设发生导入错误
,因为我试图将posts.views.post_list_view
从posts/views.py
导入另一个目录中的dj30/url.py
。教程中的那个家伙是怎么做到的?我确信我正确地遵循了教程(我做了两次)。可能是venv
有问题,因为我使用的是PyCharm
(com),而他不是
以下是在本教程中编辑的相关文件:
django/src/dj30/settings.py
:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s'
# 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',
'posts'
]
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 = 'dj30.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 = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/dj30/url.py
:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s'
# 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',
'posts'
]
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 = 'dj30.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 = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/posts/models.py
:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s'
# 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',
'posts'
]
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 = 'dj30.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 = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/posts/admin.py
:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s'
# 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',
'posts'
]
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 = 'dj30.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 = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/posts/views.py
:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s'
# 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',
'posts'
]
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 = 'dj30.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 = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/posts/templates/posts/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>This is the list of all posts.</h1>
</body>
</html>
使用runserver
运行manage.py
将生成此网站:
当我发表评论时:
from posts.views import post_list_view
及
网站显示正确:
编辑2:
转到http://127.0.0.1:8000/posts/
如建议所示:
编辑\u 3:
将url.py
更改为:
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view),
path('/', post_list_view)
]
生成此输出:
C:\Users\Artur\Desktop\django_1\venv\Scripts\python.exe C:/Users/Artur/Desktop/django_1/src/manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified some issues:
WARNINGS:
?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
System check identified 1 issue (0 silenced).
October 18, 2020 - 09:44:14
Django version 3.1.2, using settings 'dj30.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
本网站:
Pycharm正在将该行标记为红色,因为它不知道应用程序基目录。您需要单击“src”并将目录标记为源根目录,此错误才会消失 应用程序发出“找不到文件错误”,因为在主url文件“dj30/url.py”中,您没有指定“”的路径,只有“posts/”和“admin/”。要解决此问题,只需添加另一条路径:
来自django.contrib导入管理
从django.url导入路径
从posts.views导入post_list_view#错误行
URL模式=[
路径('admin/',admin.site.url),
路径('posts/',post_list_view),
路径(“”,后列表视图),
]
但是我不认为这是个错误。
而且我不相信您会希望自己运行“url.py”文件。试试这个:
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', posts_views.post_list_view)
]
@ArturMüllerRomanov转到
http://127.0.0.1:8000/posts/
@aaron请参见编辑部分<代码>http://127.0.0.1:8000/posts/似乎显示了正确的输出。这是否意味着进口有效?为什么pycharm将导入线标记为红色?为什么http://127.0.0.1:8000/
givingpage not found error
参见silvermat的答案。我标记了src
adsource root
,它解决了红色标记。我该如何解决路径问题?我添加了您提到的路径,但网站仍然出现页面未找到错误
。请参阅编辑\u 3
部分。将'/'
更改为'
。