目录:
1.需求
1.登录注册
- 编写用户注册功能(用户名、密码、确认密码)
- 提供登录功能
- 登陆后可以填写个人信息(昵称、年龄、头像)
2.功能
- 第一个注册用户为管理员,管理员还可以创建、修改、删除课程分类信息,比如(计算机、文学、化学)
- 管理员可以创建课程(每一门课程只能属于一个课程分类)、修改课程、删除课程、查看选择某一门学科的所有学生列表、查看某一分类的所有学科。
- 所有用户都可以查看课程列表,并将课程加到自己的已选课程列表中;所有用户可以查看自己选择的课程列表、查看课程详细介绍、从自己的课程列表中删除某一门课程
2.代码操作
(前端小白,所以没有加入样式QAQ)
- lessonform.py
#-*- coding:utf-8 -*-
from django.forms import Form,fields,widgets,ValidationError
from lesson import models
class register(Form):
userName = fields.CharField(max_length=10)
password = fields.CharField(max_length=10,widget=widgets.PasswordInput)
repassword = fields.CharField(max_length=10,widget=widgets.PasswordInput)
def clean(self):
password = self.cleaned_data['password']
repassword = self.cleaned_data['repassword']
if not password == repassword:
myerror = '两次密码不一致,请重新输入'
raise ValidationError(myerror)
return self.cleaned_data
class login(Form):
userName = fields.CharField(max_length=10)
password = fields.CharField(max_length=10,widget=widgets.PasswordInput)
class UserInfoForm(Form):
age = fields.IntegerField()
email = fields.EmailField(max_length=20)
class TypeForm(Form):
typeName = fields.CharField(max_length=20)
class LessonForm(Form):
lessonName = fields.CharField(max_length=20)
typeName = fields.ChoiceField()
def __init__(self,*args,**kwargs):
super(LessonForm, self).__init__(*args,**kwargs)
items = models.LessonType.objects.values_list('id','typeName')
self.fields['typeName'].choices=(x for x in items )
- models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class User(models.Model):
userName = models.CharField(max_length=10)
password = models.CharField(max_length=10)
class UserInfo(models.Model):
user = models.OneToOneField('User')
age = models.IntegerField()
email = models.EmailField()
class LessonType(models.Model):
typeName = models.CharField(max_length=20)
class Lesson(models.Model):
lessonName = models.CharField(max_length=20)
type = models.ForeignKey('LessonType')
selectedUser = models.ManyToManyField('User')
- html
- login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="{{request.path}}" method="POST">
{% csrf_token %}
<a href="{% url 'lessonregister' %}">没有账号?去注册</a><br>
用户名:{{loginform.userName}}<br>
密 码:{{loginform.password}}<br>{{error}}<br>
<input type="submit" value="登录">
</form>
<a href="{% url 'lessonlogout' %}">注销</a>
<a href="{% url 'addtype' %}">增加课程分类</a>
</body>
</html>
- html
- register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
用户名:{{form.userName}}{{error}}<br>
密 码:{{form.password}}<br>
确认密码:{{form.repassword}}<br>{{form.non_field_errors}}<br>
<input type="submit" value="注册">
<a href="{% url 'lessonlogin' %}">已有账号,去登录</a>
</form>
</body>
</html>
- html
- registersuc.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<body>
登录成功
<a href="{% url 'complete' %}">完善信息</a>
<a href="{% url 'addtype' %}">添加课程类型</a>
<a href="{% url 'addlesson' %}">添加课程</a>
<a href="{% url 'showseleteles' %}">显示已选课程</a>
<a href="{% url 'cancelseleteles' %}">取消所选课程</a>
</body>
</html>
- html
- addtype.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加课程分类</title>
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
课程类型名称:{{ form.typeName }}<br>
<input type="submit" value="添加">
</form>
</body>
</html>
-
html
- addlesson.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加课程</title>
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
课程名字:{{ form.lessonName }}<br>
课程分组:{{ form.typeName }}<br>
<input type="submit" value="确认添加">
</form>
</body>
</html>
-
html
- complete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>完善个人信息</title>
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
年龄:{{ form.age }}<br>
邮箱:{{ form.email }}<br>
<input type="submit" value="提交">
</form>
</body>
</html>
-
html
- mylesson.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示课程列表</title>
</head>
<body>
{% for item in list %}
{{ item.lessonName}}<a href="{% url 'cancelseleteles' %}?lessonid={{item.id}}">取消选修</a><br>
{% endfor %}
</body>
</html>
-
html
- show_lesson.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示课程列表</title>
</head>
<body>
{% for item in list %}
<a href="{% url 'showstudents' %}?lessonid={{item.id}}">{{ item.lessonName}}</a> <a href="{% url 'selectlesson' %}?lessonid={{item.id}}">选修此课程</a><br>
{% endfor %}
</body>
</html>
- html
- nav.html(导航栏)
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">选课系统</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="{% url 'index' %}">首页 <span class="sr-only">(current)</span></a></li>
<li><a href="{% url 'showlessontype' %}">选课</a></li>
<li><a href="{% url 'showseleteles' %}">我的课程</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="请输入关键词">
</div>
<button type="submit" class="btn btn-default">搜搜</button>
</form>
{% if not request.session.userid %}
<ul class="nav navbar-nav navbar-right">
<li><a class="btn btn-link" data-toggle="modal" href="{% url 'lessonlogin' %}">登录</a></li>
<li><a class="btn btn-link" data-toggle="modal" href="{% url 'lessonregister'%}">注册 </a> </li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">管理 <span class="caret"></span></a>
<ul class="dropdown-menu" >
<li><a href="{% url 'addtype' %}">课程分类管理</a></li>
<li><a href="{% url 'addlesson' %}">课程管理</a></li>
</ul>
</li>
</ul>
{% endif %}
{% if request.session.userid %}
<ul class="nav navbar-nav navbar-right">
<li><a class="btn btn-link" data-toggle="modal" href="{% url 'lessonlogout' %}">注销 </a> </li>
<li><a class="btn" data-toggle="modal" href="{% url 'complete' %}">我的资料</a> </li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">管理 <span class="caret"></span></a>
<ul class="dropdown-menu" >
<li><a href="{% url 'addtype' %}">课程分类管理</a></li>
<li><a href="{% url 'addlesson' %}">课程管理</a></li>
<li><a class="btn btn-link" data-toggle="modal" href="{% url 'lessonlogin' %}">登录</a></li>
<li><a class="btn btn-link" data-toggle="modal" href="{% url 'lessonregister'%}">注册 </a> </li>
</ul>
</li>
</ul>
{% endif %}
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
-
html
- showstudents.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示课程的学生</title>
</head>
<body>
{% for item in list %}
{{ item.userName }}
<br>
{% endfor %}
</body>
</html>
- 项目下的
url.py
# -*- coding:utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^register/$',views.register,name='lessonregister'),
url(r'^login/$',views.login,name='lessonlogin'),
url(r'^logout/$',views.logout,name='lessonlogout'),
url(r'^addtype/$',views.addLessonType,name='addtype'), #增加课程类型
url(r'^complete/$',views.completeInfo,name='complete'), #完善信息
url(r'^addlesson/$',views.addLesson,name='addlesson'), #增加课程
url(r'^listlesson/(\d+)/$',views.listlesson,name='listlesson'), #显示每个课程类型下的学科
url(r'^selectlesson/$',views.selectLesson,name='selectlesson'), #选课
url(r'^showseleteles/$', views.showSelectedLessons, name='showseleteles'), #显示用户已经选的课程
url(r'^cancelseleteles/$',views.cancelSelectedLessons,name='cancelseleteles'), #取消所选课程
url(r'^showstudents/$',views.showStudents,name='showstudents'), #显示每一门学科的学生
]
- views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from lesson.forms import lessonform
from lesson import models
from django.http import HttpResponse
from django.core.urlresolvers import reverse
# Create your views here.
def register(request):
if request.method == 'GET':
form = lessonform.register()
return render(request,'lesson/register.html',{'form':form})
elif request.method == 'POST':
form = lessonform.register(request.POST)
if form.is_valid():
temp = models.User.objects.filter(userName=form.cleaned_data['userName']).exists()
if temp == False:
user = models.User.objects.create(userName=form.cleaned_data['userName'],password=form.cleaned_data['password'])
request.session['userid']=str(user.id)
return HttpResponse('恭喜你注册成功,用户ID:' + request.session['userid'])
else:
error = '用户名已经存在,请换一个用户名试试!'
return render(request,'lesson/register.html',{'form':form,'error':error})
else:
return render(request,'lesson/register.html',{'form':form})
#登录功能
def login(request):
if request.method == 'GET':
loginform = lessonform.login()
return render(request,'lesson/login.html',{'loginform':loginform})
elif request.method == 'POST':
loginform = lessonform.login(request.POST,)
if loginform.is_valid():
userName = loginform.cleaned_data['userName']
password = loginform.cleaned_data['password']
user = models.User.objects.filter(userName=userName).filter(password=password)
if user.exists():
request.session['userid'] = user[0].id
print request.session['userid']
return render(request,'lesson/loginsuc.html',{'loginform':loginform})
else:
error = '用户名或者密码输入有误,请重试'
return render(request,'lesson/login.html',{'loginform':loginform,'error':error})
else:
return render(request,'lesson/login.html',{'loginform':loginform})
else:
return render(request, 'lesson/login.html')
#验证用户是否登录
def checkLogin(session):
#session 键userid如果不存在对应的值
id = session.get('userid',None)
if id==None:
#转到登录页面
return False,redirect(reverse('lessonlogin'))
else:
return True,id
#注销功能
def logout(request):
userId = request.session.get('userid',None)
if not userId == None:
del request.session['userid']
return HttpResponse('注销成功')
else:
return HttpResponse('您还没有登录')
#添加课程类型
def addLessonType(request):
#先判断是否登录
isLogin,next = checkLogin(request.session)
#登录后session中userid
if not isLogin:
return next
else:
#判断是否为第一个用户(默认第一个用户为超级管理员)
if next==1:
if request.method == 'GET':
#生成表单
form = lessonform.TypeForm()
return render(request,'lesson/addtype.html',{'form':form})
elif request.method == 'POST':
form = lessonform.TypeForm(request.POST)
if form.is_valid():
#处理表单信息
type = models.LessonType()
type.typeName = form.cleaned_data['typeName']
if not models.LessonType.objects.filter(typeName=type.typeName):
type.save()
return HttpResponse('添加成功')
else:
error='此类型已存在'
return render(request,'lesson/addtype.html',{'form':form,'error':error})
else:
return render(request,'lesson/addtype.html',{'form':form})
else:
return HttpResponse('抱歉,你没有此类权限!')
#完善信息
def completeInfo(request):
#先判断是否登录
isLogin,next = checkLogin(request.session)
# 登录后session中userid
if not isLogin:
return next
else:
if request.method == 'GET':
infoForm = lessonform.UserInfoForm()
return render(request,'lesson/complete.html',{'form':infoForm})
elif request.method == 'POST':
infoForm = lessonform.UserInfoForm(request.POST)
if infoForm.is_valid():
user = models.User.objects.get(id=request.session['userid'])
email = infoForm.cleaned_data['email']
age = infoForm.cleaned_data['age']
models.UserInfo.objects.create(user=user,age=age,email=email)
return HttpResponse('信息已经完善,你可以进行下一步操作了')
else:
return render(request,'lesson/complete.html',{'form':infoForm})
#添加课程
def addLesson(request):
#验证是否登录
isLogin,next = checkLogin(request.session)
if not isLogin:
return next
else:
#判断是否为超级管理员
if next==1:
if request.method == 'GET':
#生成表单
form = lessonform.LessonForm()
#初始化选项列表,从数据库中查找
items = models.LessonType.objects.values_list('id','typeName')
form.fields['typeName'].choices = (x for x in items)
return render(request,'lesson/addlesson.html',{'form':form})
elif request.method == 'POST':
form = lessonform.LessonForm(request.POST)
if form.is_valid():
#处理表单信息
lessonName = form.cleaned_data['lessonName']
id = form.cleaned_data['typeName']
#查找母表中的数据
lesson_type = models.LessonType.objects.get(id=id)
lesson = models.Lesson()
lesson.lessonName = lessonName
lesson.type = lesson_type
if not models.Lesson.objects.filter(lessonName=lessonName):
lesson.save()
return HttpResponse('添加成功')
else:
error = '课程已存在'
return render(request,'lesson/addlesson.html',{'form':form,'error':error})
else:
items = models.LessonType.objects.values_list('id','typeName')
form.fields['typeName'].choices=(x for x in items)
return render(request,'lesson/addlesson.html',{'form':form})
else:
return HttpResponse('你没有操作的权限!')
# 修改课程所属分类
def editlessontype(request):
#验证是否登录
isLogin,next = checkLogin(request.session)
if not isLogin:
#转到登录页面
return next
else:
if next == 1:
if request.method == 'GET':
id = request.GET['id']
obj = models.LessonType.objects.get(id=id)
form = lessonform.TypeForm(initial={
'type': obj.lessiontype
})
return render(request, 'eeditTyp.html', {'form': form, 'id': id})
elif request.method == 'POST':
form = lessonform.TypeForm(request.POST)
if form.is_valid():
data = form.cleaned_data
id = request.GET['id']
type = models.LessonType.objects.get(id=id)
type.lessiontype = data['type']
if not models.LessonType.objects.filter(lessiontype=type.lessiontype):
type.save()
return redirect(reverse('addType'))
else:
error = '课程类型已存在'
return render(request, 'edittype.html', {'form': form, 'error': error})
else:
return render(request, 'edittype.html', {'form': form})
else:
return HttpResponse('你没有此权限')
#显示课程列表
def listlesson(request):
typeId=request.GET.get('lessontypeid',0)
#lessons = models.LessonType.objects.get(id=typeId).lesson_set.all().values_list('lessonName',flat=True)
lessons = models.LessonType.objects.get(id=typeId).lesson_set.all()
return render(request,'lesson/show_lesson.html',{'list':lessons,})
#显示课程分类
def showLessonType(request):
items = models.LessonType.objects.values_list('id','typeName')
print items[0][0]
return render(request,'lesson/showlessontype.html',{'items':items})
#选课
def selectLesson(request):
lessonid = request.GET.get('lessonid',0)
lesson = models.Lesson.objects.get(id=lessonid)
user = models.User.objects.get(id=request.session['userid'])
lesson.selectedUser.add(user)
return HttpResponse('恭喜你选课成功')
#显示用户所选课程
def showSelectedLessons(request):
user = models.User.objects.get(id=request.session['userid'])
list = user.lesson_set.all()
return render(request,'lesson/mylessons.html',{'list':list})
#取消所选课程
def cancelSelectedLessons(request):
lessonid = request.GET.get('lessonid',0)
lesson = models.Lesson.objects.get(id=lessonid)
user = models.User.objects.get(id=request.session['userid'])
lesson.selectedUser.remove(user)
return HttpResponse('取消成功')
#显示一门课程的学生
def showStudents(request):
lessonid = request.GET.get('lessonid',0)
lesson = models.Lesson.objects.get(id=lessonid)
list = lesson.selectedUser.all()
return render(request,'lesson/showstudents.html',{'list':list})
# 首页
def index(request):
return render(request,'lesson/index.html')
功能持续完善中。