用户注册和登陆,验证码

共用部分:

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    """
    用户表
    """
    nid = models.BigAutoField(primary_key=True)
    username = models.CharField(verbose_name='用户名', max_length=32, unique=True)
    password = models.CharField(verbose_name='密码', max_length=64)
    nickname = models.CharField(verbose_name='昵称', max_length=32)
    email = models.EmailField(verbose_name='邮箱', unique=True)
    avatar = models.ImageField(verbose_name='头像')

    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    fans = models.ManyToManyField(verbose_name='粉丝们',
                                  to='UserInfo',
                                  through='UserFans',
                                  related_name='f',
                                  through_fields=('user', 'follower'))




class Blog(models.Model):
    """
    博客信息
    """
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='个人博客标题', max_length=64)
    site = models.CharField(verbose_name='个人博客前缀', max_length=32, unique=True)
    theme = models.CharField(verbose_name='博客主题', max_length=32)
    user = models.OneToOneField(to='UserInfo', to_field='nid')




class UserFans(models.Model):
    """
    互粉关系表
    """
    user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
    follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')

    class Meta:
        unique_together = [
            ('user', 'follower'),
        ]





class Category(models.Model):
    """
    博主个人文章分类表
    """
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='分类标题', max_length=32)

    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')






class ArticleDetail(models.Model):
    """
    文章详细表
    """
    content = models.TextField(verbose_name='文章内容', )

    article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')






class UpDown(models.Model):
    """
    文章顶或踩
    """
    article = models.ForeignKey(verbose_name='文章', to='Article', to_field='nid')
    user = models.ForeignKey(verbose_name='赞或踩用户', to='UserInfo', to_field='nid')
    up = models.BooleanField(verbose_name='是否赞')

    class Meta:
        unique_together = [
            ('article', 'user'),
        ]





class Comment(models.Model):
    """
    评论表
    """
    nid = models.BigAutoField(primary_key=True)
    content = models.CharField(verbose_name='评论内容', max_length=255)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    reply = models.ForeignKey(verbose_name='回复评论', to='self', related_name='back', null=True)
    article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
    user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')






class Tag(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='标签名称', max_length=32)
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')





class Article(models.Model):
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='文章标题', max_length=128)
    summary = models.CharField(verbose_name='文章简介', max_length=255)
    read_count = models.IntegerField(default=0)        # 阅读数
    comment_count = models.IntegerField(default=0)      # 评论
    up_count = models.IntegerField(default=0)
    down_count = models.IntegerField(default=0)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
    category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)

    type_choices = [
        (1, "Python"),
        (2, "Linux"),
        (3, "OpenStack"),
        (4, "GoLang"),
    ]

    article_type_id = models.IntegerField(choices=type_choices, default=None)

    tags = models.ManyToManyField(
        to="Tag",
        through='Article2Tag',
        through_fields=('article', 'tag'),
    )






class Article2Tag(models.Model):
    article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
    tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')

    class Meta:
        unique_together = [
            ('article', 'tag'),
        ]
models.py
def index(request,*args,**kwargs):
    """
    博客主页
    """
    # 获取当前URL
    blog = models.Blog.objects.filter().first()
    condition = {}
    type_id = int(kwargs.get('type_id')) if kwargs.get('type_id') else None
    if type_id:
        condition['article_type_id'] = type_id
    print(request.session.get('user'))
    userinfo = models.UserInfo.objects.filter(username=request.session.get('user')).first()
    type_choice_list = models.Article.type_choices
    all_count = models.Article.objects.filter(**condition).count()
    page_info = PageInfo(request.GET.get('page'), all_count, 4, '', 11)
    article_list = models.Article.objects.filter(**condition)[page_info.start():page_info.end()]
    return render(request, 'index.html',
                  {
                      'blog':blog,
                      'type_choice_list': type_choice_list,
                      'article_list': article_list,
                      'page_info': page_info,
                      'userinfo':userinfo,
                      'type_id':type_id

                  })
Views
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
    <link rel="stylesheet" href="/static/css/commons.css" />
</head>
<body>
<nav class="navbar navbar-default no-radius">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">牛掰IT技术论坛</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                {% if type_id %}
                    <li><a href="/">全部</a></li>
                {% else %}
                    <li class="active"><a href="/">全部</a></li>
                {% endif %}
                {% for item in type_choice_list %}
                    {% if item.0 == type_id %}
                        <li class="active"><a href="/all/{{ item.0 }}/">{{ item.1 }}</a></li>
                    {% else %}
                        <li ><a href="/all/{{ item.0 }}/">{{ item.1 }}</a></li>
                    {% endif %}
                {% endfor %}
            </ul>
            <div>
                <ul class="nav navbar-nav navbar-right">
                    {% if request.session.user %}
                        <li class="df"><a><img style="width: 30px;height: 30px;border-radius:65px;" src="{{ userinfo.avatar }}"></a></li>
                        <li><a>{{ request.session.user}}</a></li>
                        <li><a href="{{ request.session.user}}">我的博客</a></li>
                        <li><a href="/management.html">管理</a></li>
                        <li><a href="/log.html">退出</a></li>
                        <li><a href="/logout.html">注销</a></li>
                    {% else %}
                        <li><a href="/login.html">登录</a></li>
                        <li><a href="/logout.html">注册</a></li>
                        </ul>
                    {% endif %}
            </div>
        </div>
    </div>
</nav>
<div >
    <div class="container">
        <div class="col-md-8">
            <div class="article-list ">
                {% for article in article_list %}
                    <div class="article-item">
                        <h4 class="art-head"><a>{{ article.title }}</a></h4>
                        <div class="art-body clearfix">
                            <a class="left"><img src="{{ article.blog.user.avatar }}"></a>
                            {{ article.summary }}<a>阅读全文</a>
                        </div>
                        <div class="art-footer">
                            <a>
                                <span class="glyphicon glyphicon-user">
                                    {{ article.blog.user.nickname }}
                                    发布于{{ article.create_time|date:"Y-m-d" }}
                                    <i class="fa fa-commenting-o" aria-hidden="true"></i>
                                    {{ article.down_count }}
                                    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
                                    {{ article.up_count }}
                                </span>
                            </a>
                        </div>
                        <hr style="border:1.5px dotted darkgray"/>
                    </div>
                {% endfor %}
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        {{ page_info.pager|safe }}
                    </ul>
                </nav>
            </div>
        </div>
        <div class="col-md-4">
            <div class="panel panel-default">
                <div class="panel-heading">吐血推荐</div>
                <div class="panel-body">
                    <ul>
                        <li><p>树欲静而风不止,子欲养而亲不待。</p></li>
                        <li><p>惟将终夜长开眼,报答平生未展眉</p></li>
                        <li><p>可怜身上衣正单,心忧炭贱愿天寒?</p></li>
                        <li><p>梦里不知身是客,一晌贪欢。</p></li>
                    </ul>
                </div>
            </div>
            <div class="panel panel-default">
                <div class="panel-heading">评论最多</div>
                <div class="panel-body">
                     <ul>
                        <li><p>There is no rehearsal in the life</p></li>
                        <li><p>once missing , it will be lost forever.</p></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
index.html

static文件:—在建立—  css文件:(将commons.css放入其中)

.left{
    float: left;
}
.no-radius{
    border-radius: 0 !important;
}
.article-list .article-item .art-body a img{
    width: 80px;
    height: 80px;
}
.df{
    margin-top: -5px;
    width: 30px;
    height: 30px;
}
commons.css

 

验证码组件:(建立文件夹utils,然后把”random_check_code.py”放入其中,使用时导入即可)

def check_code(request):
    """
    验证码
    :param request: 
    :return: 
    """
    from io import BytesIO  #导入在内存
    from utils.random_check_code import rd_check_code
    img,code = rd_check_code()
    stream = BytesIO()
    img.save(stream, 'png')
    request.session['code'] = code   #把随机验证码保存在session里面
    return HttpResponse(stream.getvalue())
Views
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random

def rd_check_code(width=120, height=30, char_length=5, font_file='kumo.ttf', font_size=28):
    code = []
    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')
 
    def rndChar():
        """
        生成随机字母   
        :return:
        """
        return chr(random.randint(65, 90))
 
    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
 
    # 写文字
    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        code.append(char)
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndColor())
 
    # 写干扰点
    for i in range(20):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
 
    # 写干扰圆圈
    for i in range(30):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
 
    # 画干扰线
    for i in range(3):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
 
        draw.line((x1, y1, x2, y2), fill=rndColor())
 
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img,''.join(code)




  # 读取硬盘中的文件,在页面显示
    # f = open('static/imgs/yj.png','rb')
    # data = f.read()
    # f.close()
    # return HttpResponse(data)

    # pip3 install pillow
    # from PIL import Image
    # f = open('code.png','wb')
    # img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
    # img.save(f,'png')
    # f.close()
    #
    # f = open('code.png','rb')
    # data = f.read()
    # f.close()

    # from PIL import Image,ImageDraw,ImageFont
    # from io import BytesIO
    # """
    # f = BytesIO()
    # img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
    # draw = ImageDraw.Draw(img, mode='RGB')
    # draw.point([10, 10], fill="red")
    # draw.point([20, 10], fill=(255, 255, 255))
    #
    # draw.line((15,10,50,50), fill='red')
    # draw.line((45,20,100,100), fill=(0, 255, 0))
    #
    # draw.arc((0,0,30,30),0,360,fill="red")
    #
    # # draw.text([0,0],'python',"red")
    # # font = ImageFont.truetype("kumo.ttf", 28)
    # # draw.text([0,0],'python',(0, 255, 0),font=font)
    # import random
    #
    # # char_list = []
    # # for i in range(5):
    # #     char = chr(random.randint(65,90))
    # #     char_list.append(char)
    # # ''.join(char_list)
    #
    # # v = ''.join([ chr(random.randint(65,90)) for i in range(5)])
    #
    # char_list = []
    # for i in range(5):
    #     char = chr(random.randint(65,90))
    #     char_list.append(char)
    #     font = ImageFont.truetype("kumo.ttf", 28)
    #     draw.text([i*24,0],char,(random.randint(0,255), random.randint(0,255), random.randint(0,255)),font=font)
    # img.save(f,'png')
    # data = f.getvalue()
    # code = ''.join(char_list)
    # request.session['code'] = code
    # """
random_check_code.py

 

登陆:

class LoginForm(Form):
    user = fields.CharField(
            max_length=18,
            min_length=2,
            required=True,
            error_messages={
                'required': '用户名错误或不能为空',
                'min_length': '不能少于6位',
                'max_length': '不能大于18位',
            }
        )
    pwd= fields.CharField(
        max_length=18,
        min_length=2,
        required=True,
        error_messages={
            'required': '密码错误或不能为空',
            'min_length': '密码不能少于6位',
            'max_length': '密码不能大于18位',

        }
    )



def login(request):
    """
    用户登陆
    :param request: 
    :return: 
    """
    if request.method == "GET":
        return render(request,'login.html')
    else:
        input_code = request.POST.get('code')
        session_code=request.session.get('code')
        user = request.session.get('username')
        pwd = request.session.get('password')
        if input_code.upper() == session_code.upper():
            obj = LoginForm(request.POST)
            if obj.is_valid():
                print(obj.cleaned_data)
                if models.UserInfo.objects.filter(username=obj.cleaned_data['user'],
                                                  password=obj.cleaned_data['pwd'],
                                                  ).first():
                    user_info = models.UserInfo.objects.filter(username=user, password=pwd).values('nickname', 'email',
                                                                                                   'nid',
                                                                                                   'username', 'avatar',
                                                                                                   'blog__site',
                                                                                                   'blog__nid').first()

                    request.session['user'] = obj.cleaned_data['user']
                    request.session['user_info'] = user_info
                    return redirect('/index.html/')
            else:
                print(obj.errors)
                return render(request,'login.html',{'obj':obj})
        else:
            return render(request, 'login.html',{'msg':"验证码错误"})
Views
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
    <style>
        .login{
            width: 460px;
            margin: 0 auto;
            padding: 20px;
            margin-top: 126px;
            background-color: whitesmoke;
        }
    </style>
</head>
<body>
<div class="login">
    <h3 style="text-align: center;line-height: 65px">用户登陆</h3>
    <form class="form-horizontal" action="login.html" method="POST">
        {% csrf_token %}
        <div class="form-group">
            <label class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10 ">
                <input type="text" class="form-control" placeholder="用户名" name="user">{{ obj.errors.user.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">密&nbsp&nbsp&nbsp码</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" placeholder="密码" name="pwd">{{ obj.error.pwd.0 }}
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">验证码</label>
            <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="验证码" name="code">{{ msg }}
            </div>
            <div class="col-sm-5">
                <img onclick="change(this)"  style="width: 120px;height: 30px;" src="/check_code/" title="看不清,点我啊!">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" class="btn btn-default" value="登录"/>
            </div>
        </div>
    </form>
</div>
<script src="/static/jquery-3.2.1.js"></script>
<script>
    #刷新验证码
    function change(ths) {
        ths.src = ths.src + "?";
    }
</script>
</body>
</html>
login.html

 

注册+上传头像:

class logoutForm(Form):
    username = fields.CharField(
        max_length=18,
        min_length=2,
        required=True,
        widget=widgets.TextInput(attrs={'class':'form-control'})
    )
    nickname = fields.CharField(
        widget=widgets.TextInput(attrs={'class': 'form-control'})
    )
    email = fields.CharField(
        widget=widgets.EmailInput(attrs={'class': 'form-control'})
    )
    password = fields.CharField(
        widget=widgets.PasswordInput(attrs={'class':'form-control'})
    )
    pwd = fields.CharField(
        widget=widgets.PasswordInput(attrs={'class':'form-control'})
    )
    avatar = fields.FileField(widget=widgets.FileInput(attrs={'id':"imgSelect",'class':"ggb"}))
    code = fields.CharField(
        widget=widgets.TextInput(attrs={'class':'form-control'})
    )

    def __init__(self,request,*args,**kwargs):
        super(logoutForm,self).__init__(*args,**kwargs)
        self.request = request

    def clean_code(self):
        input_code = self.cleaned_data['code']
        session_code = self.request.session.get('code')
        if input_code.upper() == session_code.upper():
            return input_code
        raise ValidationError('验证码错误')

    def clean(self):
        p1 = self.cleaned_data.get('password')
        p2 = self.cleaned_data.get('pwd')
        if p1 == p2:
            # return self.cleaned_data
            return None
        # self.add_error(None,ValidationError('密码不一致'))
        self.add_error("pwd",ValidationError('密码不一致'))


def logout(request):
    """
    用户注册
    :param request:
    :return:
    """
    if request.method == "GET":
        obj =logoutForm(request)
        return render(request, 'logout.html', {'obj': obj})
    else:
        # 验证码操作
        obj = logoutForm(request, request.POST, request.FILES)
        if obj.is_valid():
            obj.cleaned_data.pop('pwd')
            obj.cleaned_data.pop('code')
            file_obj = request.FILES.get('avatar')
            file_path = os.path.join("static/images/temp", file_obj.name)
            with open(file_path, 'wb')as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
            print(file_path)
            obj.cleaned_data['avatar'] = file_path
            models.UserInfo.objects.create(**obj.cleaned_data)
            return redirect('/login.html')
        else:
            return render(request, 'logout.html',{'obj': obj})


import os
def upload(request):
    file_obj = request.FILES.get("avatar")
    file_path = os.path.join("static/images/temp",file_obj.name)
    with open(file_path,'wb')as f:
     for chunk in file_obj.chunks():
        f.write(chunk)
    print(file_path)
    return HttpResponse(file_path)
Views
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
    <style>
        .login{
            width: 590px;
            height: 480px;
            margin: 0 auto;
            padding: 20px;
            margin-top: 80px;
            background-color: whitesmoke;
            position: static;
        }
        .kk{
            width: 48%;
        }
        .zz{
            width: 30%;
        }
        .dq{
            margin-left:375px;
            position: relative;
            height:0px;
            width: 80px;

        }
        div img.ee{
            height:180px;
            width: 160px;
        }
        .f{
            padding: 0px 37px;
            border-radius: 0px;
        }
        .ggb{
            opacity: 0;
            position: absolute;
            height: 199px;
            width: 160px;
            top: 0px;
        }

    </style>
</head>
<body>
<div class="login">
    <h3 style="text-align: center;line-height: 65px">用户注册</h3>
    <div>
        <form class="form-horizontal " action="logout.html" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="dq">
                <img id="previewImg" class="ee" src="/static/images/default.png">
                {{ obj.avatar }}{{ obj.errors.avater.0 }}
                <button type="button" class="btn btn-default f">点击上传头像</button>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">用户名</label>
                <div class="col-sm-10 kk ">
                    {# <input type="text" class="form-control" placeholder="用户名" name="username">{{ obj.errors.user.0 }}#}
                    {{ obj.username }}{{ obj.errors.user.0 }}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">昵&nbsp&nbsp&nbsp称</label>
                <div class="col-sm-10 kk">
                    {# <input type="text" class="form-control" placeholder="昵称" name="nickname">{{ obj.error.nick.0 }}#}
                    {{ obj.nickname }}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">邮&nbsp&nbsp&nbsp箱</label>
                <div class="col-sm-10 kk">
{#                    <input type="text" class="form-control" placeholder="邮箱" name="email">{{ obj.error.email.0 }}#}
                    {{ obj.email }}{{ obj.error.email.0 }}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">密&nbsp&nbsp&nbsp码</label>
                <div class="col-sm-10 kk">
{#                    <input type="password" class="form-control" placeholder="密码" name="password">{{ obj.error.pwd.0 }}#}
                    {{ obj.password }}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">确认密码</label>
                <div class="col-sm-10 kk">
{#                    <input type="password" class="form-control" placeholder="请再次确认密码" name="pwd">{{ obj.error.pwd.0 }}#}
                    {{ obj.pwd }}{{ obj.error.pwd.0 }}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">验证码</label>
                <div class="col-sm-5 zz">
{#                    <input type="text" class="form-control" placeholder="验证码" name="code">{{ msg }}#}
                    {{ obj.code }}{{ obj.error.code.0 }}
                </div>
                <div class="col-sm-5">
                    <img onclick="change(this)" style="width: 120px;height: 30px;" src="/check_code/" title="点击更新图片">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <a href="/login.html">
                        <p><input type="checkbox" name="aihao" value="basktball" checked="checked">同意"服务条款""隐私权相关政策"</p>
                        <input type="submit" class="btn btn-default" value="注册"/>
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>
<script src="/static/jquery-3.2.1.js"></script>
<script>
    $(function(){
           bindAvatar();
        });

    function change(ths) {
        ths.src = ths.src + "?";
    }

    function bindAvatar(){
            if(window.URL.createObjectURL){
                bindAvatar2();
            }else if(window.FileReader){
                bindAvatar3()
            }else{
                bindAvatar1();
            }
        }

        /*
        Ajax上传
         */
        function bindAvatar1(){
            $('#imgSelect').change(function(){
                var obj = $(this)[0].files[0];
                var formData =new FormData();
             formData.append('avatar',obj);
             var xhr=new XMLHttpRequest();
             xhr.onreadystatechange = function(){
                 if (xhr.readyState == 4){
                     var file_path = xhr.responseText;
                     console.log(file_path);
                     var src="/"+file_path;
                     $('#previewImg').attr('src',src);
                 }
             };
             xhr.open('POST','/upload/');
             xhr.send(formData);
         })
        }
        /*
        本地上传预览
         */
        function bindAvatar2(){
            $('#imgSelect').change(function(){
                var obj = $(this)[0].files[0];
                // Ajax发送后台,并获取路径
                // img.src = 获取路径
                var v = window.URL.createObjectURL(obj);
                $('#previewImg').attr('src',v);
                $('#previewImg').load(function(){
                    window.URL.revokeObjectURL(v);
                });
            })
        }
        function bindAvatar3(){
            $('#imgSelect').change(function(){
                var obj = $(this)[0].files[0];
                // Ajax发送后台,并获取路径
                // img.src = 获取路径
                var reader = new FileReader();
                reader.onload = function(e){
                    $('#previewImg').attr('src',this.result);
                };
                reader.readAsDataURL(obj);
            })
        }

</script>
</body>
</html>
logout.html

 

案例

Python
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect, HttpResponse

def loginview(request):
    title = '后台管理'
    if request.method == 'GET':
        return render(request, 'login.html', locals())
    elif request.method == 'POST':
        username = request.POST.get('username')
        password= request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return redirect(request.GET.get('next', '/index.html'))
        error = '账号或密码错误!'
        return render(request, 'login.html', locals())
        
def logoutview(request):
    logout(request)
    return redirect('/login.html')


#本段代码来自 海瑞博客http://www.hairuinet.com/Django/201707183/index.html
 

其他函数需要权限才可以进入,我们导入模块并加在函数上即可。

from django.contrib.auth.decorators import login_required

如:

Python
@login_required
def meetview(request):
    return HttpResponse('Hello Hairui')


#本段代码来自 海瑞博客http://www.hairuinet.com/Django/201707183/index.html
 

修改密码

后端form 

Python
#form
class ChangepwdForm(Form):
    oldpassword = fields.CharField(
        required=True,
        label=u"原密码",
        error_messages={'required': u'请输入原密码'},
        widget=widgets.PasswordInput(
            attrs={'class': "form-control col-md-7 col-xs-12",
                'placeholder':u"原密码",
            }
        ),
    )
    newpassword1 = fields.CharField(
        required=True,
        label=u"新密码",
        error_messages={'required': u'请输入新密码'},
        widget=widgets.PasswordInput(
            attrs={'class': "form-control col-md-7 col-xs-12",
                'placeholder':u"新密码",
            }
        ),
    )
    newpassword2 = fields.CharField(
        required=True,
        label=u"确认密码",
        error_messages={'required': u'请再次输入新密码'},
        widget=widgets.PasswordInput(
            attrs={'class': "form-control col-md-7 col-xs-12",
                'placeholder':u"确认密码",
            }
        ),
    )
    def clean(self):
        if not self.is_valid():
            raise ValidationError(u"所有项都为必填项")
        elif self.cleaned_data['newpassword1'] != self.cleaned_data['newpassword2']:
            raise ValidationError(u"两次输入的新密码不一样")
        else:
            cleaned_data = super(ChangepwdForm, self).clean()
        return cleaned_data


#本段代码来自 海瑞博客http://www.hairuinet.com/Django/201707183/index.html
 

后端view

 
#view
@login_required
def changepwd(request):
    if request.method == 'GET':
        obj = ChangepwdForm()
        return render(request,'changepwd.html',locals())
    else:
        obj = ChangepwdForm(request.POST)
        if obj.is_valid():
            username = request.user.username
            oldpassword = request.POST.get('oldpassword', '')
            user = authenticate(username=username, password=oldpassword)
            if user is not None and user.is_active:
                newpassword = request.POST.get('newpassword1', '')
                user.set_password(newpassword)
                user.save()
                return redirect('/gitcadmin/index.html')
            else:
                oldpassword_is_wrong = True
                errmsg = '原密码不正确!请重新输入!'
                return render(request,'changepwd.html',locals())
        else:
            oldpassword_is_wrong = True
            errmsg = '2次输入密码不正确!'
            return render(request,'changepwd.html',locals())


#本段代码来自 海瑞博客http://www.hairuinet.com/Django/201707183/index.html
 

前端

Markup
<form class="form-horizontal" method="post">
    {% if oldpassword_is_wrong %}
          <div class="alert alert-error">
              <button type="button" class="close" data-dismiss="alert"</button>
              <h4>错误!</h4>{{ errmsg }}
          </div>
    {% endif %}

    <div class="form-group">
      <label for="inputEmail3" class="col-sm-2 control-label">原密码</label>
      <div class="col-sm-10">
        {{ obj.oldpassword }}
      </div>
    </div>
    <div class="form-group">{% csrf_token %}
      <label for="inputPassword3" class="col-sm-2 control-label">新密码</label>
      <div class="col-sm-10">
        {{ obj.newpassword1 }}
      </div>
    </div>
    <div class="form-group">
      <label for="inputPassword3" class="col-sm-2 control-label">确认密码</label>
      <div class="col-sm-10">
        {{ obj.newpassword2 }}
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <input type="submit" class="btn btn-success" value="确认修改">
      </div>
    </div>
  </form>


#本段代码来自 海瑞博客http://www.hairuinet.com/Django/201707183/index.htm

 

posted @ 2017-07-23 21:58  『心向阳﹡无所惧』  阅读(230)  评论(0)    收藏  举报