Django学习(实现注册功能)
1.注册功能
1).创建Django项目test,然后在test中添加应用stu:python manage.py startapp stu
在setting.py中添加新应用stu
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu' #添加新应用 stu ]
2).配置urls,stu/urls
#test\urls.py
from django.conf.urls import url, include from django.contrib import admin import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/',include('stu.urls')) ]
#test\urls.py
#coding=utf-8 from django.conf.urls import url import views urlpatterns=[ url(r'^$',views.index_view), ]
3).创建register.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/register/" method="post"> {% csrf_token %} <p> <label>用户名:<input type="text" name="uname"></label> </p> <p> <label >密 码:<input type="text" name="pwd"></label> </p> <p> <lable><input type="submit" value="注册"></lable> </p> </form> </body> </html>
4).创建学生模型 model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Student(models.Model): sname = models.CharField(max_length=30) spwd = models.CharField(max_length=30)
5).创建数据库表(当前连接sqlite3数据库)
#创建当前应用stu的迁移文件 python manage.py makemigrations stu #生成数据库表 python manage.py migrate
6).配置视图函数 view.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. from stu.models import Student def index_view(request): #1.接收请求参数 if request.method == 'GET': return render(request,'register.html') #2.非空对象 else: uname = request.POST.get("uname","") pwd = request.POST.get("pwd","") #3.创建模型对象 if uname and pwd : student = Student(sname=uname ,spwd=pwd) #4.插入数据库 student.save() return HttpResponse('注册成功') return HttpResponse("注册失败")
7).访问登录页面 127.0.0.1:8000/register/