Django项目ImportError求助:无法从project导入views
Django项目导入错误排查与解决:ImportError: cannot import name 'views' from project
项目背景
这是我的第一个Django项目,基于高校管理系统代码开发,移除了staff模块并修改了文件名。项目目录结构如下:
project asgi.py settings.py urls.py wsgi.py __init__.py media static templates sudent_information_system admin.py │ Admin_Views.py │ apps.py │ base.html │ contact.html │ forms.py │ login.html │ models.py │ registration.html │ Student_Views.py │ tests.py │ views.py │ __init__.py │ ├───migrations │ __init__.py │ ├───templates │ home.html │ └───__pycache__ admin.cpython-37.pyc apps.cpython-37.pyc models.cpython-37.pyc __init__.cpython-37.pyc
相关代码
项目根目录 urls.py
""" The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from . import views from . import HodViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', include('sudent_information_system.urls')), path('', views.home, name="home"), path('contact', views.contact, name="contact"), path('login', views.loginUser, name="login"), path('logout_user', views.logout_user, name="logout_user"), path('registration', views.registration, name="registration"), path('doLogin', views.doLogin, name="doLogin"), path('doRegistration', views.doRegistration, name="doRegistration"), # URLS for Student path('student_home/', StudentViews.student_home, name="student_home"), path('student_view_attendance/', StudentViews.student_view_attendance, name="student_view_attendance"), path('student_view_attendance_post/', StudentViews.student_view_attendance_post, name="student_view_attendance_post"), path('student_apply_leave/', StudentViews.student_apply_leave, name="student_apply_leave"), path('student_apply_leave_save/', StudentViews.student_apply_leave_save, name="student_apply_leave_save"), path('student_feedback/', StudentViews.student_feedback, name="student_feedback"), path('student_feedback_save/', StudentViews.student_feedback_save, name="student_feedback_save"), path('student_profile/', StudentViews.student_profile, name="student_profile"), path('student_profile_update/', StudentViews.student_profile_update, name="student_profile_update"), path('student_view_result/', StudentViews.student_view_result, name="student_view_result"), # URL for Admin path('admin_home/', HodViews.admin_home, name="admin_home"), path('add_course/', HodViews.add_course, name="add_course"), path('add_course_save/', HodViews.add_course_save, name="add_course_save"), path('manage_course/', HodViews.manage_course, name="manage_course"), path('edit_course/<course_id>/', HodViews.edit_course, name="edit_course"), path('edit_course_save/', HodViews.edit_course_save, name="edit_course_save"), path('delete_course/<course_id>/', HodViews.delete_course, name="delete_course"), path('manage_session/', HodViews.manage_session, name="manage_session"), path('add_session/', HodViews.add_session, name="add_session"), path('add_session_save/', HodViews.add_session_save, name="add_session_save"), path('edit_session/<session_id>', HodViews.edit_session, name="edit_session"), path('edit_session_save/', HodViews.edit_session_save, name="edit_session_save"), path('delete_session/<session_id>/', HodViews.delete_session, name="delete_session"), path('add_student/', HodViews.add_student, name="add_student"), path('add_student_save/', HodViews.add_student_save, name="add_student_save"), path('edit_student/<student_id>', HodViews.edit_student, name="edit_student"), path('edit_student_save/', HodViews.edit_student_save, name="edit_student_save"), path('manage_student/', HodViews.manage_student, name="manage_student"), path('delete_student/<student_id>/', HodViews.delete_student, name="delete_student"), path('add_subject/', HodViews.add_subject, name="add_subject"), path('add_subject_save/', HodViews.add_subject_save, name="add_subject_save"), path('manage_subject/', HodViews.manage_subject, name="manage_subject"), path('edit_subject/<subject_id>/', HodViews.edit_subject, name="edit_subject"), path('edit_subject_save/', HodViews.edit_subject_save, name="edit_subject_save"), path('delete_subject/<subject_id>/', HodViews.delete_subject, name="delete_subject"), path('check_email_exist/', HodViews.check_email_exist, name="check_email_exist"), path('check_username_exist/', HodViews.check_username_exist, name="check_username_exist"), path('student_feedback_message/', HodViews.student_feedback_message, name="student_feedback_message"), path('student_feedback_message_reply/', HodViews.student_feedback_message_reply, name="student_feedback_message_reply"), path('student_leave_view/', HodViews.student_leave_view, name="student_leave_view"), path('student_leave_approve/<leave_id>/', HodViews.student_leave_approve, name="student_leave_approve"), path('student_leave_reject/<leave_id>/', HodViews.student_leave_reject, name="student_leave_reject"), path('admin_view_attendance/', HodViews.admin_view_attendance, name="admin_view_attendance"), path('admin_get_attendance_dates/', HodViews.admin_get_attendance_dates, name="admin_get_attendance_dates"), path('admin_get_attendance_student/', HodViews.admin_get_attendance_student, name="admin_get_attendance_student"), path('admin_profile/', HodViews.admin_profile, name="admin_profile"), path('admin_profile_update/', HodViews.admin_profile_update, name="admin_profile_update"), ]
sudent_information_system/views.py
from django.shortcuts import render,HttpResponse, redirect,HttpResponseRedirect from django.contrib.auth import logout, authenticate, login from .models import Students, AdminHOD from django.contrib import messages def home(request): return render(request, 'home.html') def contact(request): return render(request, 'contact.html') def loginUser(request): return render(request, 'login_page.html') def doLogin(request): email_id = request.GET.get('email') password = request.GET.get('password') # user_type = request.GET.get('user_type') print(email_id) print(password) print(request.user) if not (email_id and password): messages.error(request, "Please provide all the details!!") return render(request, 'login_page.html') user = CustomUser.objects.filter(email=email_id, password=password).last() if not user: messages.error(request, 'Invalid Login Credentials!!') return render(request, 'login_page.html') login(request, user) print(request.user) if user.user_type == CustomUser.STUDENT: return redirect('student_home/') elif user.user_type == CustomUser.HOD: return redirect('admin_home/') return render(request, 'home.html') def registration(request): return render(request, 'registration.html') def doRegistration(request): first_name = request.GET.get('first_name') last_name = request.GET.get('last_name') email_id = request.GET.get('email') password = request.GET.get('password') confirm_password = request.GET.get('confirmPassword') print(email_id) print(password) print(confirm_password) print(first_name) print(last_name) if not (email_id and password and confirm_password): messages.error(request, 'Please provide all the details!!') return render(request, 'registration.html') if password != confirm_password: messages.error(request, 'Both passwords should match!!') return render(request, 'registration.html') is_user_exists = CustomUser.objects.filter(email=email_id).exists() if is_user_exists: messages.error(request, 'User with this email id already exists. Please proceed to login!!') return render(request, 'registration.html') user_type = get_user_type_from_email(email_id) if user_type is None: messages.error(request, "Please use valid format for the email id: '<username>.<staff|student|hod>@<college_domain>'") return render(request, 'registration.html') username = email_id.split('@')[0].split('.')[0] if CustomUser.objects.filter(username=username).exists(): messages.error(request, 'User with this username already exists. Please use different username') return render(request, 'registration.html') user = CustomUser() user.username = username user.email = email_id user.password = password user.user_type = user_type user.first_name = first_name user.last_name = last_name user.save() if user_type == CustomUser.STUDENT: Students.objects.create(admin=user) elif user_type == CustomUser.HOD: AdminHOD.objects.create(admin=user) return render(request, 'login_page.html') def logout_user(request): logout(request) return HttpResponseRedirect('/') def get_user_type_from_email(email_id): """ Returns CustomUser.user_type corresponding to the given email address email_id should be in following format: '<username>.<staff|student|hod>@<college_domain>' eg.: 'abhishek.staff@jecrc.com' """ try: email_id = email_id.split('@')[0] email_user_type = email_id.split('.')[1] return CustomUser.EMAIL_TO_USER_TYPE_MAP[email_user_type] except: return None # Create your views here.
settings.py(关键部分)
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sudent_information_system.apps.SudentInformationSystemConfig', #This object was created for us in /catalog/apps.p ] 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 = 'project.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 = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,"media") # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,"static") # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'sudent_information_system.CustomUser'
错误信息
运行项目时出现错误:
ImportError: cannot import name 'views' from project (C:\django_projects\project\project\__init__.py)
问题分析与解决方案
核心问题
项目根目录的urls.py中使用了from . import views和from . import HodViews, StudentViews,但这些视图文件并不在项目根目录(project/)下,而是位于子应用sudent_information_system/目录中。根目录下没有views.py、HodViews.py、StudentViews.py文件,导致导入失败。另外,子应用中的管理员视图文件命名为Admin_Views.py,与urls中导入的HodViews名称不匹配。
解决方案
- 修正urls.py中的导入路径
将根目录urls.py中的导入语句修改为从子应用导入:
from django.contrib import admin from django.urls import path, include # 替换原来的导入,从子应用导入视图 from sudent_information_system import views from sudent_information_system import Admin_Views as HodViews from sudent_information_system import Student_Views as StudentViews
解释:
- 子应用中的管理员视图文件是
Admin_Views.py,用Admin_Views as HodViews来匹配原来的HodViews引用 - 学生视图文件是
Student_Views.py,直接导入即可
- 清理缓存并重启服务
执行以下命令清理缓存,避免旧的导入缓存影响:
python manage.py clearcache
然后重启Django开发服务器。
- 修复views.py中的潜在问题
子应用的views.py中使用了CustomUser但未导入,需要在文件顶部添加:
from .models import CustomUser, Students, AdminHOD
否则后续会出现NameError: name 'CustomUser' is not defined的错误。
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

