Это мой первый проект на Django. Я попытался выполнить код, доступный по адресу: https://www.geeksforgeeks.org/college-management-system-using-django-python-project/
Просто внес несколько изменений, таких как удаленный модуль персонала и измененные имена файлов. Древовидная структура моего проекта показана ниже: с: управлять.py
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"),
]
Код в «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.: '[email protected]'
"""
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'
В вашем urls.py у вас есть следующие строки:
from . import views
from . import HodViews, StudentViews
Пытаюсь импортировать представления из каталога проектов, но внутри нет такого файла.
Эти файлы находятся в приложении sudent_information_system, где находится ваш файл представления, поэтому:
from sudent_information_system import views, StudentViews
obs: В структуре, которую вы разместили в своем вопросе, нет таких «HodViews», вам либо нужен файл, либо удалите его из импорта, чтобы избежать возможного перерыва.
Я хотел бы добавить, что есть официальное руководство по Django, с которого можно начать.
Трудно сказать наверняка без кода. Но похоже, что вы забыли добавить свое приложение sudent_information_system в INSTALLED_APPS в файле Django settings.py.
Спасибо за решение ошибки и ссылку на учебник. Я думаю, что был выбран неправильный проект. Тем не менее, я был бы признателен, если бы вы могли помочь мне в устранении ошибки «ModuleNotFoundError: нет модуля с именем« sudent_information_system.urls »