事前准备
进入已经配置好的虚拟环境中,激活Django的运行环境,切换至目标目录,通过django-admin startproject xxx
建立一个django工程。进入到和manage.py同级目录下,通过Python manage.py startapp zzz项目。修改XXX目录中的配置文件setting
(添加创建的项目、连接数据库、设置模板目录等),同时在工程目录下创建模板文件夹templates
、静态引用static
。
路由设置
工程同名项目中的urls.py文件
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 127.0.0.1:8000/app/stu
url(r'app/', include('app.urls', namespace='app')),
url(r'users/', include('users.urls', namespace='users')),
]
创建的项目下创建urls.py文件
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from users import views
urlpatterns = [
# 注册
url(r'^register/',views.register,name='register' ),
# 登录
url(r'^login/',views.login,name='login' ),
# 首页
url(r'^index/',login_required(views.index),name='index' ),
# 注销
url(r'^logout/',login_required(views.logout),name='logout' ),
]
函数实现
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from app.models import Student
from users.forms import UserForm, UserLoginForm
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
if request.method == 'POST':
# 校验页面中传递的参数是否完整
form = UserForm(request.POST)
# is_valid():判断表单是否验证通过
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
# 创建普通用户
User.objects.create_user(username=username, password=password)
return HttpResponseRedirect(reverse('users:login'))
else:
return render(request, 'register.html', {'form': form})
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 校验用户名和密码是否填写,校验用户名是否注册
form = UserLoginForm(request.POST)
if form.is_valid():
user = auth.authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password'])
if user:
# 用户名和密码正确
auth.login(request, user)
return HttpResponseRedirect(reverse('users:index'))
else:
# 密码不正确
return render(request, 'login.html', {'error': '密码错误'})
else:
return render(request, 'login.html', {'form': form})
def index(request):
if request.method == 'GET':
stus = Student.objects.all()
return render(request, 'index.html', {'students': stus})
def logout(request):
if request.method == 'GET':
auth.logout(request)
return HttpResponseRedirect(reverse('users:login'))
模块文件
有模型的使用就别忘了数据迁移
class Student(models.Model):
s_name = models.CharField(max_length=10, unique=True, verbose_name='姓名')
s_age = models.IntegerField(default=19, verbose_name='年龄')
s_sex = models.BooleanField(default=1, verbose_name='性别')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
operate_time = models.DateTimeField(auto_now=True, verbose_name='修改时间')
math = models.DecimalField(max_digits=4, decimal_places=2, null=True)
chinese = models.DecimalField(max_digits=4, decimal_places=2, null=True)
网友评论