django用户登录app典型代码captcha验证码

forms.py

from django.forms import ModelForm
from django import forms
from login import models
from captcha.fields import CaptchaField

class LoginForm(forms.ModelForm):
    mobile      = forms.CharField(label='手机号', min_length = 11, max_length=11)
#    password    = forms.CharField(widget=forms.PasswordInput())
#    password1   = forms.CharField(widget=forms.PasswordInput())
    captcha = CaptchaField(label='验证码')
    sms = forms.CharField(label='短信验证码', min_length = 4, max_length=4)
    
    class Meta:
        model   = models.User
        fields  = ('mobile',)
    
    def check_mobile_exist(self, mobile):
        try:
            exist = models.User.objects.get(mobile=mobile)
            if exist:
                return True
            else:
                return False
        except:
            return False

'''
    def clean_password1(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password1']:
            raise forms.ValidationError('Password don\'t match.')
        return cd['password']

'''
class ExtraMobileForm(ModelForm):
    class meta:
        model   = models.ExtraMobile
        fields  = "__all__"

models.py

# -*- encoding: utf-8 -*-
from django.db import models

# Create your models here.
class User(models.Model):
    mobile      = models.CharField(max_length = 16, unique = True)
    password    = models.CharField(max_length = 256)
    createtime  = models.DateTimeField(auto_now_add = True)
    updatetime  = models.DateTimeField(auto_now = True)
    
    def __str__(self):
        return self.mobile

class ExtraMobile(models.Model):
    user        = models.ForeignKey(User, on_delete=models.CASCADE)
    mobile      = models.CharField(max_length = 16)

    def __str__(self):
        return self.mobile

views.py

from captcha.models import CaptchaStore
from django.contrib import messages
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from login import forms
from login import models
import os 
import random

os.path

def login(request):
    login_form = forms.LoginForm()
    if request.method == "POST":
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            sesssms = request.session['sms']
            requsms = login_form.cleaned_data['sms']
            if int(sesssms) == int(requsms):
                mobile = login_form.cleaned_data['mobile']
                user = models.User.objects.create(mobile = mobile)
                return HttpResponseRedirect('/')
            else:
                messages.warning(request, '短信验证码错误')
        else:
            messages.warning(request, '表单数据没有通过验证')
    else:
        sms = random.randint(1000, 9999)
        request.session['sms'] = sms 
    
    return render(request, 'login.html', locals())

# 客户端通过ajax方式提交验证码,返回json格式,校验正确返回1,错误返回0
def ajax_val(request):
    if request.is_ajax():
        cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
        if cs:
            json_data={'status':1}
        else:
            json_data={'status':0}
        return JsonResponse(json_data)
    else:
        json_data={'status':0}
        return JsonResponse(json_data)

login.html

{% extends 'base.html' %}
{% load static %}
{% block css %}
	<link rel="stylesheet"  href="{% static "login/css/login.css" %}" />
{% endblock %}
{% block headerjs %}
	<script src="{% static "login/js/login.js" %}"></script>
{% endblock %}
{% block content %}
{% for message in messages %}
	<div class="alert alert-{{message.tags}}">{{ message }}</div>
{% endfor %}
<p>{{ sms }}</p>
	<form name="myform" method="post">
		{% csrf_token %}
		<table>
			{{ login_form.as_table }}
		</table>
		<input type="submit" value="submit">

	</form>
{% endblock %}

login.js



$(document).ready(function(){
        $('#id_sms').attr('disabled', 'disabled');
        $('#id_captcha_1').attr('disabled', 'disabled');

        // 判断手机号输入
        $('#id_mobile').keyup(function(){
                if($('#id_mobile').val().length == 11){
                        $('#id_captcha_1').removeAttr('disabled').focus();
                }
        });

        
        // captcha ajax刷新
        $('.captcha').css({'cursor':'pointer'})
        $('.captcha').click(function(){
                console.log('click');
                $.getJSON('/captcha/refresh/', function(result){
                        $('.captcha').attr('src', result['image_url']);
                        $('#id_captcha_0').val(result['key'])
                });
        });
        // 判断验证码输入
        $('#id_captcha_1').keyup(function(){
                if($('#id_captcha_1').val().length == 4){
                        json_data={
                            'response':$('#id_captcha_1').val(), // 获取输入框和隐藏字段id_captcha_0的数值
                            'hashkey':$('#id_captcha_0').val()
                        }
                        $.getJSON('/ajax_val', json_data, function(data){
                         //ajax发送
                                $('#captcha_status').remove();
                                if(data['status']){ //status返回1为验证码正确, status返回0为验证码错误, 在输入框的后面写入提示信息
                                        $('#id_sms').removeAttr('disabled').focus();    
                                        $('#captcha_status').remove();
                                }
                                else{
                                        $('#id_captcha_1').after('*验证码错误')
                                }
                        });
                }
        });
});


你可能感兴趣的:(python3,Django3,ajax)