bbs论坛注册功能(1)
分析项目需求创建表:
STATICFILE_DIR = [ os.path.join(BASE_DIR,'static') #设置目录,bootstrip添加到目录中去,直接本地调用 ] # auth默认表 AUTH_USER_MODEL='app01.UserInfo' # 医用应用app01的userinfo表,不在使用默认的user表
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # 定义用户表 class UserInfo(AbstractUser): phone = models.BigIntegerField(null=True) create_time = models.DateField(auto_now_add=True) # 存储头像文件,把文件存放到avatar目录下,只存放路径信息 avatar = models.FileField(upload_to='avatar/', default='avatar/default.png') blog= models.OneToOneField(to='Blog',null=True) # 定义个人站点表 class Blog(models.Model): # 站点名称 site_name = models.CharField(max_length=32) # 站点标题 site_title = models.CharField(max_length=32) # 个人站点样式文件,存该样式文件的路径 theme = models.CharField(max_length=64) # 文章分类表 class Category(models.Model): name = models.CharField(max_length=64) blog = models.ForeignKey(to='Blog',null=True) # 文章标签表 class Tag(models.Model): name = models.CharField(max_length=32) blog = models.ForeignKey(to='Blog',null=True) # 文章表 class Article(models.Model): # 文章标题 title = models.CharField(max_length=64) # 文章简介 desc = models.CharField(max_length=256) # 文章详情,TextField存储大量文本 content = models.TextField() # 文章创建时间 create_time= models.DateField(auto_now_add=True) # 查询优化 # 评论数 comment_num = models.IntegerField() # 点赞数 up_num = models.IntegerField() # 点踩数 down_num = models.IntegerField() blog = models.ForeignKey(to='Blog',null=True) category = models.ForeignKey(to='Category',null=True) # 隐藏关联表 tags = models.ManyToManyField(to='Tag',through='Article2Tags',through_fields=('article','tag')) # 创建article与tags的关系表第三张表 class Article2Tags(models.Model): article = models.ForeignKey(to='Article') tag = models.ForeignKey(to='Tag') # 点赞点踩表 class UpAndDown(models.Model): # 用户 user= models.ForeignKey(to='UserInfo') # 文章字段 article = models.ForeignKey(to='Article') # 存点赞数 is_up = models.BooleanField() # 文章评论表 class Commnet(models.Model): # 用户字段 user=models.ForeignKey(to='UserInfo') # 文章字段 article = models.ForeignKey(to='Article') # 评论内容 content = models.CharField(max_length=256) # 评论时间 create_time = models.DateField(auto_now_add=True) # 父评论 parent = models.ForeignKey(to='self',null=True)
设置后台views.py
from django.shortcuts import render,HttpResponse
from app01 import myforms
def register(reques):
form_obj = myforms.MyForm() return render(reques,'register.html',locals())
前端设置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册账号</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>注册页面</h1> <form id="myform"> {% csrf_token %} {% for foo in form_obj %} <div class="form-group"> <label for="{{ foo.auto_id }}">{{ foo.label }}</label> {{ foo }} {# 加载对应输入框的提示信息#} <span class="errors"></span> </div> {% endfor %} </form> <div class="form-group"> {# 点击图片也可以删除文件#} <label for="id_myfile">头像 <img src="/static/img/default.png" alt="" width="60" style="margin-left: 10px"> </label> <input type="file" name="myfile" id="id_myfile" style="display: none"> </div> <button class="btn btn-primary pull-right">注册</button> </div> </div> </div> </body> </html>
实现点击头像上传图片后在头像上显示上传的头像
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册账号</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>注册页面</h1> <form id="myform"> {% csrf_token %} {% for foo in form_obj %} <div class="form-group"> <label for="{{ foo.auto_id }}">{{ foo.label }}</label> {{ foo }} {# 加载对应输入框的提示信息#} <span class="errors"></span> </div> {% endfor %} </form> <div class="form-group"> {# 点击图片也可以删除文件#} <label for="id_myfile">头像 <img src="/static/img/default.png" alt="" width="80" style="margin-left: 10px" id="id_img"> </label> <input type="file" name="myfile" id="id_myfile" style="display: none"> </div> <button class="btn btn-primary pull-right">注册</button> </div> </div> </div> <script> $('#id_myfile').change(function () { //获取上传的文件对象 let fileobj=this.files[0]; //生成一个文件阅读器对象 let fileReader = new FileReader(); //将文件独放入文件阅读器中 fileReader.readAsDataURL(fileobj); {#fileReader文件读取图片完成后再进行渲染#} ///动态显示头像 //等待文件加载完毕后在展示 fileReader.onload = function(){ //将读取出文件对象替换到img标签 $('#id_img').attr('src',fileReader.result) } }) </script> </body> </html>
往后端传送数据使用ajax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册账号</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>注册页面</h1> <form id="myform"> {% csrf_token %} {% for foo in form_obj %} <div class="form-group"> <label for="{{ foo.auto_id }}">{{ foo.label }}</label> {{ foo }} {# 加载对应输入框的提示信息#} <span class="errors pull-right" style="color: red"></span> </div> {% endfor %} </form> <div class="form-group"> {# 点击图片也可以删除文件#} <label for="id_myfile">头像 <img src="/static/img/default.png" alt="" width="80" style="margin-left: 10px" id="id_img"> </label> <input type="file" name="myfile" id="id_myfile" style="display: none"> </div> <button class="btn btn-primary pull-right" id="id_submit">注册</button> </div> </div> </div> <script> $('#id_myfile').change(function () { //获取上传的文件对象 let fileobj=this.files[0]; //生成一个文件阅读器对象 let fileReader = new FileReader(); //将文件独放入文件阅读器中 fileReader.readAsDataURL(fileobj); {#fileReader文件读取图片完成后再进行渲染#} ///动态显示头像 //等待文件加载完毕后在展示 fileReader.onload = function(){ //将读取出文件对象替换到img标签 $('#id_img').attr('src',fileReader.result) } }); //ajax提交数据 $('#id_submit').click(function () { //生成一个formdata对象 let formData = new FormData(); //往formData中添加键值 $.each($('#myform').serializeArray(), function (index, obj) { {#console.log(index,obj)#} formData.append(obj.name,obj.value) }); //手动添加文件数据 formData.append('myfile',$('#id_myfile')[0].files[0]); $.ajax({ url:'', type:'post', //发送formData需要制定参数,数据不做处理 data:formData, processData:false, contentType:false, success:function (data) { console.log(data) if (data.code == 100){ //跳转页面 location.href = data.url } else{ $.each(data.msg,function (index,obj) { console.log(index,obj) let targetID = '#id_'+ index; //id_username,id_password $(targetID).next().html(obj[0]) }) } } }) $('input').focus(function () { $(this).next().html('') }) }) </script> </body> </html>
from django.shortcuts import render from app01 import myforms from app01 import models from django.http import JsonResponse # Create your views here. def register(request): back_dic={'code':100,'msg':''} form_obj = myforms.MyForm() if request.method == 'POST': form_obj = myforms.MyForm(request.POST) print(request.POST) # 判断数据是否存在,存在返回true,不存在返回false print(form_obj.errors) print(form_obj.is_valid()) if form_obj.is_valid(): data = form_obj.cleaned_data # 将coonfirm_password去除掉 data.pop('confirm_password') # 获取用户上传头像文件 file_obj = request.FILES.get('myfile') # 判断用户是否上传了自己的头像 if file_obj: # 数据库中头像路径字段是avator data['avatar']=file_obj models.UserInfo.objects.create_user(**data) back_dic['msg']= '注册成功' back_dic['url']='/login/' else: back_dic['code']=101 # 错误信息返回前台 back_dic['msg']=form_obj.errors return JsonResponse(back_dic) return render(request, 'register.html', locals())
实现效果:前台输入信息完成注册,输入错误提示红色信息,再次点击窗扣错误信息消失