1.admin的概念
# Admin是Django自带的一个功能强大的自动化数据管理界面 # 被授权的用户可以直接在Admin中操作数据库 # Django提供了许多针对Admin的定制功能
2. 配置并管理自动化界面
# 终端项目目录创建一个超级用户:python3 manage.py createsuperuser # eg:Username:root | Email:[email protected] | Password:1234qwer # 浏览器Admin入口:http://127.0.0.1:8000/admin # 设置Admin界面为中文环境:项目下settings.py,LANGUAGE_CODE = ‘zh-Hans‘ # 简体:zh-hans | 繁体:zh-hant | 美式英语:en-us
3. 把数据库的表自动注册到admin 界面内
from django.contrib import admin # Register your models here. from blog.models import * admin.site.register(User) admin.site.register(Blog) admin.site.register(Article) admin.site.register(Category) admin.site.register(Tag) admin.site.register(UpOrDown) admin.site.register(Comment)
4. 自定义显示字段名与表名:
# 为应用下models.py映射关系类重写__str__方法 class Article(models.Model): title = models.CharField(max_length=32, default=‘Title‘, verbose_name="标题") content = models.TextField(null=True, verbose_name="内容", blank=True) # 重写__str__方法,格式化该类实例对象的表示方式 def __str__(self): return self.title class Meta: verbose_name = "文章" verbose_name_plural = verbose_name
如何创建一个验证码给用户注册的时候使用
from django.shortcuts import render, HttpResponse from django.http import JsonResponse from blog.checks import check_name, CheckForm from blog.models import User from django.contrib.auth import authenticate, login # 安装Pillow模块 # 生成图片(画板)、字体(选择指定ttf并设置字体)、画笔(画点、线、字、圆) from PIL import Image, ImageFont, ImageDraw from io import BytesIO import random # 定义接口规范 response_dic = { ‘statue‘: 1, ‘msg‘: ‘ok‘, ‘data‘: {} } # 创建画板,保存在服务器本地 def save_local(): img = Image.new(‘RGB‘, (230, 32), (40, 20, 10)) # type: Image # 本地写流 wf = open(‘code.png‘, ‘wb‘) # 将数据以指定格式丢给文件操作流 img.save(wf, ‘png‘) with open(‘code.png‘, ‘rb‘) as f: data = f.read() return data
创建画板,保存在服务器本地
# 随机RGB元组 def random_RGB(min, max): return tuple([random.randint(min, max) for i in range(3)]) # 随机产生六位验证码 def random_six_code(): code = "" # 每一位均可以为字母大写、小写或数字 for i in range(6): tag = random.randint(1, 3) # 1:大写 2:小写 3:数字 if tag == 1: code += chr(random.randint(65, 90)) elif tag == 2: code += chr(random.randint(97, 122)) else: code += str(random.randint(0, 9)) return code
随机产生六位数的验证码
# 获取验证码 def login_code(request): # data = save_local() img = Image.new(‘RGB‘, (230, 32), random_RGB(150, 255)) # 在画板中画字 img_draw = ImageDraw.Draw(img) # 设置ImageFont字体 img_font = ImageFont.truetype(‘static/font/kumo.ttf‘, size=30) # 获取六位验证码 img_code = random_six_code() # 将img_code存储到session中,与会话绑定,用来完成登录验证码的验证 request.session[‘img_code‘] = img_code # 画文字:xy轴、文本、颜色、ImageFont字体 for i, ch in enumerate(img_code): img_draw.text((30 + i * 30, 0), ch, random_RGB(0, 150), img_font) bf = BytesIO() img.save(bf, ‘png‘) data = bf.getvalue() # 从内存中将数据全部取出 return HttpResponse(data)
获取验证码
# 登录 def my_login(request): if request.method == "GET": return render(request, ‘login.html‘) if request.method == "POST": client_code = request.POST.get(‘img_code‘, None).lower() server_code = request.session.get(‘img_code‘, None).lower() print("client_code", client_code) print("server_code", server_code) if client_code != server_code: return JsonResponse({ ‘statue‘: 2, ‘msg‘: "验证码错误", ‘data‘: {} }) # 验证通过就可以进行用户登录 username = request.POST.get(‘username‘, None) password = request.POST.get(‘password‘, None) user = authenticate(username=username, password=password) if user: login(request, user) return JsonResponse({ ‘statue‘: 1, ‘msg‘: "登录成功", ‘data‘: {} }) return JsonResponse({ ‘statue‘: 2, ‘msg‘: "登录失败", ‘data‘: {} })
login方法+判断验证码是否正确
from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^$‘, views.my_login), url(r‘^register/$‘, views.register), url(r‘^check_username/$‘, views.check_username), url(r‘^my_login/$‘, views.my_login), # 获取验证码的GET请求 url(r‘^login_code/$‘, views.login_code), ]
在url内设置好验证码的路径,方便ajax调用
<script> $(".login").click(function () { token = $(‘[name=csrfmiddlewaretoken]‘).val(); $.ajax({ url: ‘/my_login/‘, type: ‘post‘, data: { {#csrfmiddlewaretoken: ‘{{ csrf_token }}‘,#} csrfmiddlewaretoken: token, username: $(‘#username‘).val(), password: $(‘#password‘).val(), img_code: $(‘#img_code‘).val(), }, success: function (data) { console.log(data); $("#login-info").modal(‘show‘); $(‘#myModalLabel‘).text(data.msg) } }) }) $(‘#code‘).click(function () { {#var _this = this;#} {#$.ajax({#} {# url: ‘/login_code/‘,#} {# success: function (data) {#} {# console.log(data);#} {# $(_this).attr(‘src‘, data)#} {# }#} {# })#} url = ‘/login_code/‘; var xhr = new XMLHttpRequest(); xhr.open(‘GET‘, url, true); // url xhr.responseType = "blob"; xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var blod = this.response; var src = URL.createObjectURL(blod); // src $(‘#code‘).attr(‘src‘, src); } } }; xhr.send(); }) </script>
前端ajax识别验证码的方法
原文地址:https://www.cnblogs.com/gukai/p/10776393.html
时间: 2024-10-08 14:49:03