您好,登錄后才能下訂單哦!
python安裝官網
pip install django(==2.2.0) //不加版本默認安裝最新版
在安裝完成后要配置好需要的第三方庫:(pip下載,推薦在pycharm下也配置虛擬環境)
Django2.2
連接mysql需要的庫:PyMySQL, mysql, mysqlclinet
驗證碼用到的庫:django-simple-captcha
(只需在虛擬環境下配置)
(由于下載庫較多,忘記用到的庫,下附截圖)
我使用的是MySQL,推薦安裝界面管理文件(我使用的是MySQLWorkbench)數據庫配置,settings.py文件
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'cet', #數據庫名字 'USER':'root', #登陸數據庫的用戶名 'PASSWORD':'123', #登陸數據庫的密碼 'HOST':'localhost', #數據庫的ip地址 'PORT':'3306', #ip地址的端口號,默認(3306) } }
__init__.py里面導入pymysql
import pymysql pymysql.install_as_MySQLdb()
django-admin startproject project_name #創建項目 python manage.py startapp app_name #創建app(可能會報錯) #上面創建app失敗用下面這個指令 django-admin startapp app_name 1.2.2 注冊app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', #登錄注冊 'captcha', #驗證碼 'home', #報名主頁 ]
settings.py文件中,將默認改為亞洲/上海和中文
LANGUAGE_CODE = 'zh-hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False
更改models.py后,要將更改同步到數據庫之中,這時就要用到數據庫遷移指令(若遷移失敗:no changes問題)。
python manage.py makemigrations python manage.py migrate
命令行沖使用指令創建管理員賬號用于使用django自帶的框架。
python manage.py createsuperuser
添加端口號:
(我將其放在了app名為login里面)
特殊參數說明:verbose_name——用于修改django框架各表成員的名字(相當于副名,只用于顯示),其他可以從文章
開頭推薦的博客了解。
#login/models.py from django.db import models # Create your models here. class User(models.Model): '''用戶表''' gender = ( ('male', '男'), ('female', '女'), ) name = models.CharField(verbose_name="用戶名", max_length=128, unique=True) # unique表示唯一 password = models.CharField(verbose_name="密碼", max_length=256) email = models.EmailField(verbose_name="郵箱", unique=True) sex = models.CharField(verbose_name="性別", max_length=32, choices=gender, default='男') c_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name #用于將django自帶管理員端漢化 class Meta: ordering = ['c_time'] verbose_name = '用戶' verbose_name_plural = '用戶'
#login/admin.py from django.contrib import admin # Register your models here. from . import models admin.site.register(models.User)
在我們創建數據庫用戶表后,采用表單驗證前端的數據并進行存儲到數據庫中。
#login/forms.py from django import forms from captcha.fields import CaptchaField class user_entry(forms.Form): user_name = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) user_true_name = forms.CharField(label="真實姓名", max_length=128,widget=forms.TextInput(attrs={'class': 'form-control'})) user_id = forms.CharField(label="身份證號", max_length=18, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(label="郵箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'})) exam_point = forms.CharField(label="考點", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) class user_datas(forms.Form): email = forms.EmailField(label="郵箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'})) user_name = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) user_true_name = forms.CharField(label="真實姓名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) user_id = forms.CharField(label="身份證號", max_length=18, widget=forms.TextInput(attrs={'class': 'form-control'})) # user_img = user_school = forms.CharField(label="所在學校", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) # user_f_score = forms.CharField(label="四級成績", max_length=10, widget=forms.TextInput(attrs={'class': 'form-control'})) # user_s_score = forms.CharField(label="六級成績", max_length=10, widget=forms.TextInput(attrs={'class': 'form-control'}))
由于登陸注冊使用的路徑不多,就將其全放在項目目錄下的urls.py文件,當然也可以采用項目和app相結合。
#項目名/urls.py from django.contrib import admin from django.urls import path,include from login import views urlpatterns = [ path('', views.index), #修改端口默認主頁 path('admin/', admin.site.urls), #管理員端 #登錄注冊 path('index/', views.index), path('check/', views.check), path('login/', views.login), path('register/', views.register), path('logout/', views.logout), #使用驗證碼 path('captcha', include('captcha.urls')), #報名app路由 path('homepage/',include('home.urls')), ]
#login/views.py from django.shortcuts import render, redirect from . import models from .forms import UserForm,RegisterForm from home.models import user_data # Create your views here. def check(request): pass return render(request, 'login/hello.html') def index(request): pass return render(request, 'login/index.html') #加入sesson def login(request): #不允許重復登錄 if request.session.get('is_login', None): return redirect('/index') if request.method == "POST": login_form = UserForm(request.POST) message = "請檢查填寫的內容!" if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] try: user = models.User.objects.get(name=username) if user.password == password: #往session字典內寫入用戶狀態和數據 request.session['is_login'] = True request.session['user_id'] = user.id request.session['user_name'] = user.name return redirect('/index/') else: message = "密碼不正確!" except: message = "用戶不存在!" return render(request, 'login/login.html', locals()) login_form = UserForm() return render(request, 'login/login.html', locals()) def logout(request): if not request.session.get('is_login', None): # 如果本來就未登錄,也就沒有登出一說 return redirect("/index/") request.session.flush() # 或者使用下面的方法 # del request.session['is_login'] # del request.session['user_id'] # del request.session['user_name'] return redirect("/index/") def register(request): if request.session.get('is_login', None): # 登錄狀態不允許注冊。 return redirect("/index/") if request.method == "POST": register_form = RegisterForm(request.POST) message = "請檢查填寫的內容!" if register_form.is_valid(): # 獲取數據 username = register_form.cleaned_data['username'] password1 = register_form.cleaned_data['password1'] password2 = register_form.cleaned_data['password2'] email = register_form.cleaned_data['email'] sex = register_form.cleaned_data['sex'] if password1 != password2: # 判斷兩次密碼是否相同 message = "兩次輸入的密碼不同!" return render(request, 'login/register.html', locals()) else: same_name_user = models.User.objects.filter(name=username) if same_name_user: # 用戶名唯一 message = '用戶已經存在,請重新選擇用戶名!' return render(request, 'login/register.html', locals()) same_email_user = models.User.objects.filter(email=email) if same_email_user: # 郵箱地址唯一 message = '該郵箱地址已被注冊,請使用別的郵箱!' return render(request, 'login/register.html', locals()) message = "注冊成功!" # 當一切都OK的情況下,創建新用戶 # 創建用戶信息//有問題:放在創建用戶表后面會出現DJANGO pymysql.err.IntegrityError: # (1062, "Duplicate entry '' for key 'user_name'") new_user_data = user_data.objects.create() new_user_data.user_name = username new_user_data.user_true_name = '無' new_user_data.user_id = '無' new_user_data.user_school = '無' # new_user_data.user_f_score = 425 # new_user_data.user_s_score = 0 new_user_data.save() #創建用戶表 new_user = models.User.objects.create() new_user.name = username new_user.password = password1 new_user.email = email new_user.sex = sex new_user.save() return redirect('/login/') # 自動跳轉到登錄頁面 register_form = RegisterForm() return render(request, 'login/register.html', locals())
(我將其放在了app名為home里面)
#home/models.py from django.db import models # Create your models here. class exam_entry_table(models.Model): #考點信息表 exam_id = models.CharField(verbose_name="考試編號",max_length=10) exam_type = models.CharField(verbose_name="考試類別",max_length=128) exam_point = models.CharField(verbose_name="考點",max_length=128) exam_time = models.CharField(verbose_name="考試時間",max_length=128) number = models.IntegerField(verbose_name="容量") entry_number = models.IntegerField(verbose_name="已報名數量",default=0) def __str__(self): return self.exam_point class Meta: # ordering = ['c_time'] verbose_name = '考點' verbose_name_plural = '考點信息表' class user_entry_table(models.Model): #用戶考試信息表 email = models.EmailField(verbose_name="郵箱") exam_id = models.CharField(verbose_name="考試編號",max_length=10) exam_point = models.CharField(verbose_name="考點",max_length=128) def __str__(self): return self.email class Meta: # ordering = ['c_time'] verbose_name = '用戶考試信息' verbose_name_plural = '用戶考試信息表' class user_data(models.Model): #用戶信息表 user_name = models.CharField(verbose_name="用戶名",max_length=128, unique=True) user_true_name = models.CharField(verbose_name="真實姓名",max_length=128, null=True) user_id = models.CharField(verbose_name="身份證號",max_length=18, null=True) # user_img = user_school = models.CharField(verbose_name="在讀學校",max_length=128) user_f_score = models.IntegerField(verbose_name="四級成績", default=0) user_s_score = models.IntegerField(verbose_name="六級成績", default=0) def __str__(self): return self.user_name class Meta: # ordering = ['c_time'] verbose_name = '用戶名' verbose_name_plural = '用戶信息表'
#home/admin.py from django.contrib import admin # Register your models here. from . import models admin.site.register(models.exam_entry_table) #考點信息表 admin.site.register(models.user_entry_table) #用戶考試信息表 admin.site.register(models.user_data) #用戶信息表
#home/forms.py from django import forms from captcha.fields import CaptchaField class UserForm(forms.Form): username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) captcha = CaptchaField(label='驗證碼') class RegisterForm(forms.Form): gender = ( ('male', "男"), ('female', "女"), ) username = forms.CharField(label="用戶名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label="密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(label="確認密碼", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'})) email = forms.EmailField(label="郵箱地址", widget=forms.EmailInput(attrs={'class': 'form-control'})) sex = forms.ChoiceField(label='性別', choices=gender) captcha = CaptchaField(label='驗證碼')
這里用到的路勁較為復雜,采用項目urls和app的urls結合起來避免項目的urls過于擁擠。
先修改項目的urls.py文件:
#項目名/urls.py path('homepage/',include('home.urls')), #前面已經添加了,這里只做說明
再修改app中的urls.py文件:
#home/urls.py from django.contrib import admin from django.urls import path,include from home import views urlpatterns = [ path('test/', views.test), path('my_data/',views.mydate), #我的信息 path('query_results/',views.query), #查詢報告信息 path('cet_4/',views.cet_4), #四級報名 path('cet_6/',views.cet_6), #六級報名 path('change_my_data/',views.updata), ]
#home/views.py from django.shortcuts import render, redirect from . import models from .forms import user_entry, user_datas from django.http import HttpResponse,HttpResponseRedirect # from django.contrib.auth.models import User from login.models import User # Create your views here. def test(request): pass return render(request, 'home/test.html') #我的信息 def mydate(request): username = request.session.get('user_name', None) account = User.objects.get(name=username)#用戶登錄注冊表 user = models.user_data.objects.get(user_name= username) return render(request,"home/myself.html",{"user":user, "account":account}) #修改我的信息 def updata(request): username = request.session.get('user_name', None) # print("-----------------------") # print(username) # print("-----------------------") user_da = models.user_data.objects.get(user_name=username) user = User.objects.get(name=username)#login_user表 if request.method == "POST": userdata = user_datas(request.POST) # print(userdata) if userdata.is_valid(): user_das = userdata.cleaned_data # user.user_name = user_da['user_name'] #用戶無法修改用戶名 user.email = user_das['email'] user_da.user_true_name = user_das['user_true_name'] user_da.user_id = user_das['user_id'] user_da.user_school = user_das['user_school'] user_da.save() user.save() # 四六級成績無法修改 # user_datas.user_f_score = user_da['user_f_score'] # user_datas.user_s_score = user_da['user_s_score'] return redirect('/homepage/my_data/') else: userdata = user_datas(initial={"email":user.email,"user_name":user_da.user_name,"user_true_name":user_da.user_true_name,"user_id":user_da.user_id,"user_school":user_da.user_school}) return render(request, 'home/change_mydata.html', {"userdata":userdata}) #查詢考試信息 還沒完成,優化,條件判斷 def query(request): username = request.session.get('user_name',None) user = User.objects.get(name=username) #用于判斷用戶是否報名 user_en = models.user_entry_table.objects.filter(email=user.email) # print("********************") # print(user_en) # print(user_en[0]) if user_en: # print(len(user_en)) if len(user_en)==1: user_entry = models.user_entry_table.objects.get(email=user.email) user_point = user_entry.exam_point user_eid = user_entry.exam_id exam_entry = models.exam_entry_table.objects.get(exam_point=user_point, exam_id=user_eid) return render(request, 'home/query1.html', {"exam_entry": exam_entry}) else: user_entry4 = models.user_entry_table.objects.get(email=user.email, exam_id=0) user_entry6 = models.user_entry_table.objects.get(email=user.email, exam_id=1) user_point4 = user_entry4.exam_point user_point6 = user_entry6.exam_point exam_entry4 = models.exam_entry_table.objects.get(exam_point=user_point4, exam_id=0) exam_entry6 = models.exam_entry_table.objects.get(exam_point=user_point6, exam_id=1) return render(request, 'home/query2.html', {"exam_entry4": exam_entry4, "exam_entry6":exam_entry6}) else: # message = "你還未報名!請先報名之后再來查看!" # return render(request, 'login/index.html', locals()) user_da = models.user_data.objects.get(user_name=user.name) school = user_da.user_school if school=='無': message = "請先更新你的學校信息!" return render(request, 'login/index.html', locals()) else: point = models.exam_entry_table.objects.filter(exam_point=school) if point: if len(point)==1: exam = models.exam_entry_table.objects.get(exam_point=school) return render(request, 'home/exam1.html', {"exam": exam}) else: exam4 = models.exam_entry_table.objects.get(exam_point=school, exam_id=0) exam6 = models.exam_entry_table.objects.get(exam_point=school, exam_id=1) return render(request, 'home/exam2.html', {"exam4": exam4, "exam6": exam6}) else: message="你的學校還未開放報名!詳情請咨詢學校相關部門!" return render(request, 'login/index.html', locals()) #四級報名 def cet_4(request): username = request.session.get('user_name', None) # 用戶信息表,用戶表,獲取信息判斷資格 user_da = models.user_data.objects.get(user_name=username) user = User.objects.get(name=username) if request.method == "POST": cet4_form = user_entry(request.POST) if cet4_form.is_valid(): # 四級考試對分數無要求 # 只需要獲取報考考點信息即可 # email = cet4_form.cleaned_data['email'] exam_id = '0' exam_point = cet4_form.cleaned_data['exam_point'] #用與下面的考點判斷 point = models.exam_entry_table.objects.filter(exam_point=exam_point, exam_id='0') # 用與下面的是否重復報名判斷 entryer = models.user_entry_table.objects.filter(email=user.email, exam_id=exam_id) #判斷個人信息是否完善 if user_da.user_true_name=='無'or user_da.user_id=='無': message="請先完善個人真實信息之后再來報名!" return render(request, 'home/cet_4.html', locals()) # 判斷是否重復報名 # print("判斷是否重復報名") elif entryer: message = "請勿重復報名!" return render(request, 'home/cet_4.html', locals()) elif point: # 考點存在 # print("沒有重復報名") message = "報名成功!請按時參加考試!" # 創建一條數據 new_user = models.user_entry_table.objects.create() new_user.email = user.email new_user.exam_id = exam_id new_user.exam_point = exam_point new_user.save() # 考點容量減1,報考人數加1 exam_entry = models.exam_entry_table.objects.get(exam_point=exam_point, exam_id=exam_id) exam_entry.number -= 1 exam_entry.entry_number += 1 exam_entry.save() return render(request, 'home/cet_4.html', locals()) else: message = "該學校還未開放報名!詳情請咨詢學校相關部門!" return render(request, 'home/cet_4.html', locals()) cet4_form = user_entry(initial={"email": user.email, "user_name": user_da.user_name, "user_true_name": user_da.user_true_name, "user_id": user_da.user_id}) return render(request, 'home/cet_4.html', locals()) #六級報名: def cet_6(request): username = request.session.get('user_name', None) # 用戶信息表,用戶表,獲取信息判斷資格 user_da = models.user_data.objects.get(user_name=username) user = User.objects.get(name=username) if request.method == "POST": cet6_form = user_entry(request.POST) if cet6_form.is_valid(): # 只需要獲取報考考點信息即可 # email = cet4_form.cleaned_data['email'] exam_id = '1' exam_point = cet6_form.cleaned_data['exam_point'] f_score = user_da.user_f_score # 用與下面的考點判斷 point = models.exam_entry_table.objects.filter(exam_point=exam_point, exam_id=exam_id) # 用與下面的是否重復報名判斷 entryer = models.user_entry_table.objects.filter(email=user.email, exam_id=exam_id) # 判斷個人信息是否完善 if user_da.user_true_name=='無'or user_da.user_id=='無': message="請先完善個人真實信息之后再來報名!" return render(request, 'home/cet_6.html', locals()) # 判斷是否重復報名 elif entryer: # print("判斷是否重復報名") message = "請勿重復報名!" return render(request, 'home/cet_6.html', locals()) # 判斷考點是否存在 elif point: # 考點存在 #判斷四級成績是否合格 if f_score >= 425: # print("報名成功!請按時參加考試!") # 創建一條數據 message = "報名成功!請按時參加考試!" new_user = models.user_entry_table.objects.create() new_user.email = user.email new_user.exam_id = exam_id new_user.exam_point = exam_point new_user.save() # 考點容量減1,報考人數加1 exam_entry = models.exam_entry_table.objects.get(exam_point=exam_point, exam_id=exam_id) exam_entry.number -= 1 exam_entry.entry_number += 1 exam_entry.save() return render(request, 'home/cet_6.html', locals()) else: message = "四級成績大于425才能報名六級考試!" return render(request, 'home/cet_6.html', locals()) else: message = "該學校還未開放報名!詳情請咨詢學校相關部門!" return render(request, 'home/cet_6.html', locals()) cet6_form = user_entry( initial={"email": user.email, "user_name": user_da.user_name, "user_true_name": user_da.user_true_name, "user_id": user_da.user_id}) return render(request, 'home/cet_6.html', locals())
到這里基本的后端都實現了。
成果展示:
注冊:
登錄:
主頁:
管理端:
數據庫設計問題:
由于此次設計在開始之時沒有設計完善,數據庫各表之間的關聯存在問題,例如本次報名系統而言,用戶信息最好添加手機號碼,我本打算使用郵箱即可,但是推薦使用聯系更快的電話號碼等等問題。
附錄
整體項目包地址鏈接: https://pan.baidu.com/s/130AP7coMP_U2q_dzaazUWA 提取碼: nywa
總結
以上所述是小編給大家介紹的Pycharm+django2.2+python3.6+MySQL實現簡單的考試報名系統,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。