程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django logs in with a picture verification code and an email or mobile number

編輯:Python

Realize the page effect

Realize the idea

  • Use form Render data
  • Check cell phone number ( Format 、 Register or not )、 Password and verification code

Generate image captcha

''' pillow: yes python The module that processes pictures , Very powerful '''
import random
from PIL import Image, ImageDraw, ImageFont
def picture_code():
def get_char():
''' Get... Through numbers ASCII Corresponding letters in the table '''
return chr(random.randint(65, 90))
def get_color():
''' Get random colors '''
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# mode: Color system size: Wide and high color: Color 
# RGB Color chart :https://tool.oschina.net/commons?type=3
img = Image.new(mode='RGB', size=(120, 50), color=(220, 220, 220))
# Create a brush object 
draw = ImageDraw.Draw(img, mode='RGB')
# Draw a dot xy: Coordinates based on pictures ,fill: Color 
for i in range(10):
draw.point([random.randint(0, 120), random.randint(0, 50)], fill='green')
# Draw line xy:( Starting point coordinates , End coordinates ),width: thickness 
for i in range(5):
draw.line(
[random.randint(0, 120), random.randint(0, 50), random.randint(0, 120), random.randint(0, 50)],
fill='red'
)
# Draw a circle or arc start and end: angle 
for i in range(3):
x = random.randint(0, 120)
y = random.randint(0, 50)
x2 = x + 4
y2 = y + 4
draw.arc([x, y, x2, y2], start=0, end=90, fill='red')
# Be careful :.ttf The file path cannot contain Chinese 
font = ImageFont.truetype('fonts/domi.ttf', 35)
char_list = []
for i in range(5):
char = get_char()
char_list.append(char)
height = random.randint(10, 15)
draw.text([18 * (i + 1), height], text=char, fill='red', font=font)
char_code = ''.join(char_list)
return img, char_code
if __name__ == '__main__':
img, r = picture_code()
# Create in memory , Here, it is directly generated locally , It is convenient for you to adjust and view 
with open('code.png', 'wb') as f:
img.save(f, format='png') # format: Format 
print(r)

Display the verification code on the page

First, the backend needs to define a route and view for generating verification code .

path('img_code/', account.img_code, name='img_code'),
def img_code(request):
img, char_code = picture_code()
# Write picture data to memory 
stream = BytesIO()
img.save(stream, format='png')
# Put the verification code in session in You can also put it in redis in 
request.session['image_code'] = char_code
# The validity of the picture verification code , Unit second 
request.session.set_expiry(settings.IMAGE_CODE_EXPIRY)
return HttpResponse(stream.getvalue())

How to display the verification code in the front page :

 <img id="img_code" height="34" width="120" src="{% url "img_code" %}" alt="">

Full page code :

<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="account">
<h2 class="text-center"> The user login </h2>
<form id="form_data">
{
% csrf_token %}
{
% for field in form %}
{
% if field.label == ' Verification Code ' %}
<div class="form-group">
<label for="{
{ field.id_for_label }}">{
{
 field.label }}</label>
<div class="row">
<div class="col-xs-6">
{
{
 field }}
<span class="error_msg"></span>
</div>
<div class="col-xs-6">
<img id="img_code" height="34" width="120" src="{% url "img_code" %}" alt="">
</div>
</div>
</div>
{
% else %}
<div class="form-group">
<label for="{
{ field.id_for_label }}">{
{
 field.label }}</label>
{
{
 field }}
<span class="error_msg"></span>
</div>
{
% endif %}
{
% endfor %}
<div>
<button type="button" id="login" class="btn btn-primary"> deng record </button>
<div class="pull-right">
<a href="{% url 'login_sms' %}"> SMS verification code login >>></a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

Send login data and click refresh verification code :

// Send login data
function sendLoginData() {

// Get all the data entered by the user
// Send data to back end
// Perform some page effect processing according to the response results
// Bind click event
$('#login').click(function () {

var data = $('#form_data').serialize(); // Get form All the data in the form
$.ajax({

url: '{% url 'login' %}',
type: 'post',
data: data,
success:function (res) {

if (res.status){

location.href = res.path;
}else{

$.each(res.error_msg,function (k,v){

$('#id_' + k).next().text(v)
})
}
}
})
})
}
// Click the event to refresh the image verification code
function refreshImageCode() {

$('#img_code').click(function () {

var oldSrc = $(this).attr('src');
$(this).attr('src',oldSrc + '?'); // The question mark will resend the request
})
}

views.py:

def login(request):
if request.method == 'GET':
form = LoginForm(request)
return render(request, 'user/login.html', dict(form=form))
else:
form = LoginForm(request, data=request.POST)
if form.is_valid():
return JsonResponse(dict(status=True, path=reverse('index')))
else:
return JsonResponse(dict(status=False, error_msg=form.errors))

form Check class :

from django import forms
from django.core.exceptions import ValidationError
from django.db.models import Q
from web import models
from web.utils.bootstrap_style import BootStrapForm
from web.utils.enc import set_md5
class LoginForm(BootStrapForm, forms.Form):
''' Log in with your mobile number or email address '''
username = forms.CharField(label=' Mobile number or email ')
password = forms.CharField(widget=forms.PasswordInput, label=' password ')
image_code = forms.CharField(label=' Verification Code ')
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
def clean_password(self):
''' Password encrypted transmission '''
password = self.cleaned_data.get('password')
return set_md5(password)
def clean_image_code(self):
''' Verify the picture captcha * The user input should be consistent with that saved in the background '''
user_code = self.cleaned_data.get('image_code', '')
session_code = self.request.session.get('image_code', '')
if not session_code:
raise ValidationError(' The verification code has expired !!')
if user_code.strip().upper() != session_code.upper():
raise ValidationError(' Verification code error !!!')
return session_code
def clean(self):
''' Mobile phone number and email verification '''
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
uname_or_email = models.UserInfo.objects.filter(
Q(Q(phone=username)| Q(email=username)),
password=password
).exists()
if not uname_or_email:
self.add_error('username',' Wrong user name or password !!')
return self.cleaned_data

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved