一、项目说明
学习django版本1.8.2,把之前零散学习的知识整合下,主要涉及到:
项目开始,ajax数据调用,注册,数据录入,数据修改,数据删除,数据建模等完成一个完整的前后台功能简单的web。数据库默认用sqlite
1、创建djano项目:
$cd /data1/DjangoProject/ $django-admin startproject School $cd School $python manage.py startapp student $mkdir template static
用pycharm打开School项目结构如图:
2、基础配置
$cd /data1/DjangoProject/School/School
$vim settings.py
添加App student 如图:
修改template路径 如图:
修改static 路径 如图:
3、数据库(sqlite)建模:
在student目录下新建 models.py内容如下:
#coding:utf-8 from django.db import models # Create your models here. class Student(models.Model): name = models.CharField(max_length=32,verbose_name="姓名") Gender = models.CharField(max_length=16, verbose_name="性别") Age = models.IntegerField(verbose_name="年龄") Birthday = models.DateField(verbose_name="生日") Grade = models.CharField(max_length=32, verbose_name="年级") subject = models.CharField(max_length=32, verbose_name="专业") city = models.CharField(max_length=32, verbose_name="城市")
4、同步数据库
$/data1/DjangoProject/School
$python manage.py validate 如图:
$python manage.py makemigrations 如图:
$python manage.py syncdb 如图:
二、完成注册功能register.html
1、form表单定义:
在student app目录下创建form.py 内容如下:
#coding:utf-8 from django import forms class StudentForm(forms.Form): name = forms.CharField(max_length=32,label="姓名",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) Gender = forms.CharField(max_length=16, label="性别",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) Age = forms.IntegerField(label="年龄",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) #required = False 表示可为空 Birthday = forms.DateField(label="生日",widget=forms.TimeInput(attrs = {"class":"form-contorl"}),required=False) Grade = forms.CharField(max_length=32, label="年级",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) subject = forms.CharField(max_length=32, label="专业",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) city = forms.CharField(max_length=32, label="城市",widget=forms.TimeInput(attrs = {"class":"form-contorl"})) def clean_name(self): ##函数名必须是clear_上面的字段 固定格式 name = self.cleaned_data["name"] if name[0].isalpha(): return name else: raise forms.ValidationError("The first must be character.")
2、简单register.html
在template目录创建register.html刚开始内容可为空
3、为register.hmtl创建视频和路由
视图views.py中定义register视图函数内容如下:
#coding:utf-8 from models import Student from form import StudentForm from django.shortcuts import render from django.shortcuts import render_to_response # Create your views here. def register(request): return render(request,"register.html",locals())
在/data1/DjangoProject/School/School/urls.py中添加 内容如下图:
开启项目访问:http://127.0.0.1:8000/register 得到一个空白页
三、完善register.html
1、在/data1/DjangoProject/School/static/目录下分别创建 css目录放入bootstrap.min.css
js目录放入jquery-3.1.1.min.js vue.min.js img目录中有两张图片, 目录结构如图:
以上内容主到http://down.51cto.com/data/2334389下载
2、register.html网页内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户注册</title> <script type="text/javascript" src="/static/js/jquery-3.1.1.min.js"></script> <script type="text/javascript" src="/static/js/vue.min.js"></script> <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> } </head> <body background="/static/img/bg2.png"> <h1 style="text-align: center;color:white" > Student Register <hr/> </h1> <form class="form-inline" style="text-align: center" method="post"> {% csrf_token %} <!-- post方法csrf 标识 --> {{ sForm.as_p }} <input class="form-control" type="submit" value="注册"> </form> <!--ajax 表单验证用户名--> <script> $( function () { $("#id_name").blur( function () { var name = $("#id_name").val() $.ajax( { url:"/valide_name/", type:"get", data:{"name":name}, success:function (data) { // $("#id_name").val("name is exsit") console.log(data) }, error:function (err) { console.log(err) } } ) } ) } ) </script> </body> </html>
3、修改views.py中的register视图函数
#coding:utf-8 from models import Student from form import StudentForm from django.http import JsonResponse from django.shortcuts import render from django.shortcuts import render_to_response # Create your views here. def register(request): if request.method == "POST" and request.POST: #判断提交的数据方式是Post并且有数据 sForm = StudentForm(request.POST) #将post数据交给form表单进行验证 if sForm.is_valid(): #判断form表单提交的数据是否正确 clean_data = sForm.cleaned_data #获取验证过的数据 s = Student() s.name = clean_data["name"] s.Gender = clean_data["Gender"] s.Age = clean_data["Age"] s.Birthday = clean_data["Birthday"] s.Grade = clean_data["Grade"] s.subject = clean_data["subject"] s.city = clean_data["city"] s.save() else: pass else: sForm = StudentForm() return render(request,"register.html",locals()) #对name值限制必须以字符开头,函数固定格式valide_field def valide_name(request): if request.method == "GET" and request.GET: name = request.GET[‘name‘] if Student.objects.filter(name=name): # if name == id_name: name = "we have a %s" % name else: name = name else: name = "No name" result = {"data":name} return JsonResponse(result)
四、访问验证
打开浏览器访问http://172.16.3.140:8000/register/如图:添加几条测试数据
类似添加完几条后打开sqlite数据库数据如下:
2、验证ajax对name的焦点移开请求验证是否存在
打开浏览器F12调试功能
先再次输入san 移开鼠标 会看到console中出现we have san 如图:
换成其他的用户名如 ling520如图:
到此一个带sqlite数据库 结合django 的注册页面 通过 ajax完成验证功能完成,其他内容后续补充。