ajax写登录页面

静态配置

STATICFILES_DIRS = (
        os.path.join(BASE_DIR,'my_blog','static'),
)
AUTH_USER_MODEL = "app01.UserInfo"
setting

表结构:models

from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserInfo(AbstractUser):   #settings  :AUTH_USER_MODEL ="项目名称.UserInfo"
    '''用户信息表'''
    nid = models.BigAutoField(primary_key=True)
    nickname =models.CharField(max_length=32,verbose_name="昵称",unique=True)
    tel = models.IntegerField(verbose_name="电话",unique=True,null=True,blank=True)
    email = models.CharField(max_length=64,verbose_name="邮箱")
    avatar = models.FileField(verbose_name="头像",upload_to="avatar",default="/avatar/default.png")
    create_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True)

    class Meta:
        verbose_name_plural = "用户信息表"
    def __str__(self):
        return self.username

class Article(models.Model):
    '''
    文章表
    '''
    title = models.CharField(max_length=64,verbose_name="文章标题")
    summary = models.CharField(max_length=244, verbose_name="文章概要")
    create_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="修改时间",auto_now=True)
    poll_count = models.IntegerField(verbose_name="点赞数",default=0)
    comment_count = models.IntegerField(verbose_name="评论数",default=0)
    read_count = models.IntegerField(verbose_name="阅读数",default=0)
    # is_essence = models.BooleanField(verbose_name="是否精华",default=0)
    # is_top = models.BooleanField(verbose_name="是否置顶",default=0)

    user = models.ForeignKey(to="UserInfo",verbose_name="所属作者",null=True,blank=True)
    classify = models.ForeignKey(to="Classfication",verbose_name="所属类别",null=True,blank=True)
    tags = models.ManyToManyField(to="Tag",through="Article2tag",through_fields=('article', 'tag'),verbose_name="所属标签")
    type_choices = [
        (1,"编程语言"),
        (2,"软件设计"),
        (3,"前端系列"),
        (4,"数据库"),
        (5,"操作系统")
    ]
    artcle_type_id = models.IntegerField(choices=type_choices,default=None)
    class Meta:
        verbose_name_plural = "文章表"
    def __str__(self):
        return self.title

class Article_detail(models.Model):
    '''文章细节表'''
    article = models.OneToOneField(to="Article",verbose_name="所属文章")
    content =models.TextField(max_length=400,verbose_name="文章内容")

    class Meta:
        verbose_name_plural = "文章细节表"

class Tag(models.Model):
    '''标签表'''
    name = models.CharField(max_length=32,verbose_name="标签名")
    blog = models.ForeignKey(to="Blog",verbose_name="所属博客")
    class Meta:
        verbose_name_plural = "标签表"

class Article2tag(models.Model):
    article = models.ForeignKey(verbose_name="文章",to="Article")
    tag = models.ForeignKey(verbose_name="标签",to="Tag")
    class Meta:
        '''联合唯一'''
        unique_together = [
            ("article","tag")
        ]

class Comment(models.Model):
    '''评论表'''
    time = models.DateTimeField(verbose_name="评论时间",auto_now_add=True)
    content = models.CharField(max_length=265,verbose_name="评论内容")
    up_count = models.IntegerField(default=0)
    user = models.ForeignKey(to="UserInfo",verbose_name="评论人",null=True,blank=True)
    article = models.ForeignKey(to="Article",verbose_name="评论文章",null=True,blank=True)
    farther_comment = models.ForeignKey(to="Comment",verbose_name="父级评论",null=True,blank=True)
    # farther_comment = models.ForeignKey("self",verbose_name="父级评论",null=True,blank=True)

    class Meta:
        verbose_name_plural = "评论表"

class Article_poll(models.Model):
    '''文章点赞表'''
    time = models.DateTimeField(verbose_name="点赞时间",auto_now_add=True)
    article = models.ForeignKey(to="Article",verbose_name="点赞文章",null=True,blank=True)   #一个文章可以有多个赞
    user = models.ForeignKey(to="UserInfo",verbose_name="点赞人",null=True,blank=True)
    # is_positive = models.BooleanField(default=1,verbose_name="点赞或踩")

    class Meta:
        '''联合唯一'''
        unique_together = ("user", "article",)
        verbose_name_plural = "文章点赞表"

class Comment_poll(models.Model):
    '''评论点赞表'''
    time=models.DateTimeField(verbose_name="点赞时间",auto_now_add=True)
    # is_positive = models.BooleanField(verbose_name="点赞或踩",default=1)
    user = models.ForeignKey(to="UserInfo",verbose_name="点赞用户",null=True,blank=True)
    comment = models.ForeignKey(to="Comment",verbose_name="点赞所属评论",null=True,blank=True)   #一个评论可以有多个赞

    class Meta:
        '''联合唯一'''
        unique_together = ("user","comment",)
        verbose_name_plural = "评论点赞表"

class Blog(models.Model):
    '''个人站点表'''
    title = models.CharField(max_length=32,verbose_name="个人博客标题")
    url = models.CharField(max_length=64,verbose_name="路径",unique=True)
    theme = models.CharField(max_length=32,verbose_name="博客主题")
    user = models.OneToOneField(to="UserInfo", verbose_name="所属用户")
    class Meta:
        '''通过admin录入数据的时候个中文显示'''
        verbose_name_plural = "个人站点表"

    def __str__(self):
        return self.title

class Classfication(models.Model):
    '''博主个人文章分类表'''
    title = models.CharField(max_length=32, verbose_name="分类标题")
    blog = models.ForeignKey(to="Blog",verbose_name="所属博客")

    class Meta:
        verbose_name_plural = "分类表"
models

 

HTML:先引入bootstrap

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/dist/js/jquery-3.1.1.js"></script>
    <script src="/static/dist/js/bootstrap.js"></script>

    <link rel="stylesheet" href="/static/dist/css/bootstrap.css">

    <link rel="stylesheet" href="/static/css/login.css">
</head>
<body>

<div class="container">

    <div class="row">
        <div class="col-md-5 col-md-offset-3">
            <form><h1>欢迎您进入登陆页面</h1>
                {% csrf_token %}
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" class="form-control" id="username" placeholder="用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" class="form-control" id="password" placeholder="密码">
                </div>

                <div class="row validCode">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="validCode">验证码</label>
                            <input type="text" class="form-control validCode_text" id="validCode"
                                   placeholder="验证码">
                        </div>
                    </div>
                    <div class="col-md-6">

                        <img class="validCode_img" src="/get_validCode_img/" alt="" width="200px" height="50px">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">

                      <p> <span class="error"></span> <input type="button" value="登录" class="btn btn-primary btn-block " id="sub"></p>
                    </div>
                    <div class="col-md-6">
                        <input type="button" value="注册" class="btn btn-success btn-block " id="sub">
                    </div>
                </div>

            </form>
        </div>
    </div>
</div>

<script>
    $("#sub").click(function () {
        $.ajax({
            url: "/login/",
            type: "POST",
            data: {
                "username": $("#username").val(),
                "password": $("#password").val(),
                "validCode": $("#validCode").val(),
                "csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val(),

            },
            success: function (data) {
                console.log(data)
                var response = JSON.parse(data);
                if (response["is_login"]) {
                    location.href = "/index/"
                }
                else {
                    $(".error").html(response["error_msg"]).css("color", "yellow")
                }
            }

        })
    })
</script>

</body>
</html>
login
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login),
    url(r'^get_validCode_img/',views.get_validCode_img),
url

视图函数:views

from django.shortcuts import render,redirect,HttpResponse
from app01 import models
from app01 import  *
from my_blog import settings
from django.contrib import auth

def login(request):
    if request.is_ajax():
        username=request.POST.get("username")
        password=request.POST.get("password")
        validCode=request.POST.get("validCode")

        login_response = {"is_login": False, "error_msg": None}
        if validCode.upper() == request.session.get("keepValidCode").upper():
            user = auth.authenticate(username=username, password=password)
            if user:
                login_response["is_login"] = True
                auth.login(request, user)

            else:
                login_response["error_msg"] = "username or password error"

        else:
            login_response["error_msg"] = 'validCode error'

        import json

        return HttpResponse(json.dumps(login_response))

    return render(request, "login.html")

def get_validCode_img(request):
    from io import BytesIO
    import random

    from PIL import Image,ImageDraw,ImageFont
    img = Image.new(mode="RGB", size=(120, 40),
                    color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

    draw = ImageDraw.Draw(img, "RGB")
    font = ImageFont.truetype("my_blog/static/font/kumo.ttf", 25)

    valid_list = []
    for i in range(5):
        random_num = str(random.randint(0, 9))
        random_lower_zimu = chr(random.randint(65, 90))
        random_upper_zimu = chr(random.randint(97, 122))

        random_char = random.choice([random_num, random_lower_zimu, random_upper_zimu])
        draw.text([5 + i * 24, 10], random_char,
                  (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), font=font)
        valid_list.append(random_char)
        # 画点
        for i in range(40):
            draw.point([random.randint(0, 120), random.randint(0, 40)])

        # 画线
        #     for i in range(5):
        #         draw.line(
        #             (random.randint(0, 120), random.randint(0, 40), random.randint(0, 120), random.randint(0, 40)))

    f = BytesIO()
    img.save(f, "png")
    data = f.getvalue()
    #
    valid_str = "".join(valid_list)
    print(valid_str)

    request.session["keepValidCode"] = valid_str

    return HttpResponse(data)
views

 

posted @ 2017-12-04 11:53  Dear坏小子  阅读(156)  评论(0编辑  收藏  举报