报障系统之博客主页及后台管理

Posted bigdata_devops

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了报障系统之博客主页及后台管理相关的知识,希望对你有一定的参考价值。

个人博客:

url函数(路由系统):

"""baozhang URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r\'^$\', views.home, name=\'home\')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r\'^$\', Home.as_view(), name=\'home\')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r\'^blog/\', include(\'blog.urls\'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^all/(?P<type_id>\\d+)/\', views.index),
    url(r\'^login/\', views.login),
    url(r\'^logout/\', views.logout),
    url(r\'^check_code/\', views.check_code),

    url(r\'^register/\', views.register),注册页面

    url(r\'^(?P<site>\\w+)/(?P<key>((tag)|(category)|(date)))/(?P<val>\\w+-*\\w*).html$\', views.home_filter),#筛选
    url(r\'^(?P<site>\\w+).html$\', views.home),#个人已开通博客主页
    url(r\'^(?P<site>\\w+)/p/(?P<nid>\\w+).html$\', views.detail),  # 文章详细
    url(r\'^(?P<site>\\w+)/(?P<nid>\\d+).html$\', views.article),#评论
    url(r\'^up.html$\', views.up),#点赞或踩
    url(r\'^lizhi-(?P<article_type_id>\\d+)-(?P<categpry_id>\\d+)-(?P<tags_id>\\d+).html$\', views.lizhi),
    url(r\'^upload/\', views.upload),#上传

    # url(r\'^openblog/\', views.openblog),
    # url(r\'^(\\w+)/\', views.blog),
    url(r\'^test/\', views.test),
    # url(r\'^(\\w+)/$\', views.home),
    url(r\'^\', views.index),#个人主页
]

报障系统主页

def index(request, *args, **kwargs):
    """
    个人主页
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    # print(request.path_info)  # /all/1/  /all/2/
    username = request.session.get(\'username\')
    obj = models.UserInfo.objects.filter(username=username).values(\'blog__site\').first()


    condition = {}
    type_id = int(kwargs.get(\'type_id\')) if kwargs.get(\'type_id\') else None  # 如果kwargs.get(\'type_id\')有值时转成整型没有值等于None
    if type_id:
        condition[\'article_type_id\'] = type_id

    article_list = models.Article.objects.filter(**condition)
    # article_type_id = models.IntegerField(choices=type_choices, default=None)
    type_choice_list = models.Article.type_choices  # 文章分类
    user_list = models.UserInfo.objects.filter()
    return render(
        request,
        \'index.html\',
        {
            \'username\': username,
            \'obj\': obj,
            \'type_id\': type_id,
            \'type_choice_list\': type_choice_list,
            \'article_list\': article_list,
        }
    )
个人主页函数

Class Form类

注册类:

from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from app01 import models

class RegisterForm(Form):
    username = fields.CharField(
        required=True,
        widget=widgets.TextInput(
            attrs={\'class\':\'form-control\',\'placeholder\':\'用户名为6-10个字符\'}
        ),
        min_length=6,
        max_length=10,
        strip=True,
        error_messages={
            \'required\': \'用户名不能为空\',
            \'min_length\':\'用户名至少为6个字符\',
            \'max_length\':\'用户名不超过10个字符\',
        },
    )
    password = fields.CharField(
        required=True,
        widget=widgets.PasswordInput(
            attrs={\'class\':\'form-control\',\'placeholder\':\'密码为8-12个字符\'}
        ),
        min_length=8,
        max_length=12,
        strip=True,
        validators=[
            RegexValidator(r\'((?=.*\\d))^.{8,12}$\',\'必须包含数字\'),
            RegexValidator(r\'((?=.*[a-zA-Z]))^.{8,12}\',\'必须包含字母\'),
            # RegexValidator(r\'((?=.*[^a-zA-Z0-9]))^.{8,12}\',\'必须包含特殊字符\'),
            # RegexValidator(r\'^.(\\s){8,12}\',\'必须包含空格\'),
        ],#用于对密码的正则验证
        error_messages={
            \'required\': \'密码不能为空\',
            \'min_length\':\'密码不能少于8个字符\',
            \'max_length\':\'密码最多为12个字符!\',
        }
    )
    password_again = fields.CharField(
        required=True,
        widget=widgets.PasswordInput(
            attrs={\'class\':\'form-control\',\'placeholder\':\'密码为8-12个字符\'}
        ),
        min_length=8,
        max_length=12,
        strip=True,
        error_messages={\'required\':\'请再次输入密码!\',}
    )
    nickname = fields.CharField(
        required=True,
        widget=widgets.TextInput(
            attrs={\'class\':\'form-control\',\'placeholder\':\'请输入昵称\'}
        )
    )
    email = fields.EmailField(
        required=True,
        widget=widgets.TextInput(attrs={\'class\':\'form-control\',\'placeholder\':\'请输入邮箱\'}),
        # strip=True,
        # error_messages={\'required\':\'邮箱不能为空\',\'invalid\':\'请输入正确的邮箱格式\'},
    )
    avatar = fields.FileField(widget=widgets.FileInput(attrs={\'id\':\'imgFile\',\'class\':\'f1\'}))
    code = fields.CharField(widget=widgets.TextInput(attrs={\'class\':\'form-control\',\'placeholder\':\'请输入验证码\'}))
    def clean_username(self):
        #对于username扩展验证,查看是否存在
        username = self.cleaned_data[\'username\']
        users = models.UserInfo.objects.filter(username=username).count()
        if users:#如果用户名已存在
            raise ValidationError(\'用户名已经存在!\')
        return username
    def clean_email(self):
        #对于email的扩展验证,查看是否存在
        email = self.cleaned_data[\'email\']
        email_count = models.UserInfo.objects.filter(email=email).count()
        if email_count:
            raise ValidationError(\'邮箱已经存在!\')
        return email
    # def _clean_password(self):#验证两次输入密码是否一致
    #     password1 = self.cleaned_data[\'password\']
    #     password2 = self.cleaned_data[\'password_again\']
    #     if password1 and password2:
    #         if password1 != password2:
    #             raise ValidationError(\'您两次输入的密码不一致\')

    def __init__(self,request,*args,**kwargs):#构造方法,传request参数
        super(RegisterForm,self).__init__(*args,**kwargs)#完成原有form功能以外
        self.request = request#再封装一个request

    def clean_code(self):
        input_code = self.cleaned_data[\'code\']
        session_code = self.request.session.get(\'code\')#session取验证码
        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(\'password_again\')
        if p1 == p2:
            # return self.cleaned_data
            return None
        # else:
        #     raise ValidationError(\'密码不一致\')
        self.add_error("password_again",ValidationError(\'密码不一致\'))

            # except ValidationError as e:
            # self.add_error(name, e)
    # def clean(self):
    #     #基于form对象的验证,字段全部验证通过会调用clean函数验证
    #     self._clean_password()#调用函数
    #     p1 = self.cleaned_data[\'password\']
    #     p2 = self.cleaned_data[\'password_again\']
    #     return p2

    # def clean_password(self):
    #     p1 = self.cleaned_data[\'password\']
    #     p2 = self.cleaned_data[\'password_again\']
        return p2
RegisterForm类(加一个构造方法)

登录类:

class LoginForm(forms.Form):
    """用户登录form验证"""
    username = fields.CharField(
        required=True,
        widget=widgets.TextInput(attrs={\'class\': \'form-control\', \'placeholder\': \'请输入用户名\'}),
        min_length=6,
        max_length=10,
        strip=True,
        error_messages={\'required\': \'用户名不能为空\', }
    )
    password = fields.CharField(
        required=True,
        widget=widgets.TextInput(attrs={\'class\': \'form-control\', \'placeholder\': \'请输入密码\'}),
        max_length=12,
        min_length=8,
        strip=True,
        error_messages={\'required\': \'密码不能为空\', }
    )

    def clean(self):
        username = self.cleaned_data.get(\'username\')
        password = self.cleaned_data.get(\'password\')
        user_list = models.UserInfo.objects.filter(username=username).first()
        if username and password:
            if not user_list:
                raise ValidationError(\'用户名不存在,请重新输入\')
            elif password != user_list.password:
                raise ValidationError(\'密码错误\')
LoginForm类

用户登录视图函数

# 用户登录
def login(request):  # GET请求
    """
    用户登录
    :param request:
    :return:
    """
    if request.method == "GET":
        obj = LoginForm()
        return render(request, \'login.html\', {\'obj\': obj})
    else:
        # print(request.POST)

        # obj = LoginForm(request.POST)

        # errors = {}
        # print(obj.errors)
        # print(obj)
        # print(request.session)
        # if obj.is_valid():
        input_code = request.POST.get(\'code\')
        # print(input_code)
        session_code = request.session.get(\'code\')
        if input_code.upper() == session_code.upper():  # 判断验证码是否正确
            username = request.POST.get(\'username\')
            user_list = models.UserInfo.objects.filter(username=username).first()
            print(user_list)
            if user_list:
                password = request.POST.get(\'password\')
                if user_list.password == password:
                    request.session[\'is_login\'] = \'true\'
                    request.session[\'username\'] = user_list.username
                    return redirect(\'/\')
                else:
                    msg = \'密码错误\'
                    obj = LoginForm(request.POST)
                    return render(request, \'login.html\', {\'msg\': msg, \'obj\': obj})
            else:
                msg = \'该账号不存在\'
                obj = LoginForm(request.POST)
                return render(request, \'login.html\', {\'msg\': msg, \'obj\': obj})
        else:
            msg = \'验证码错误\'
            obj = LoginForm(request.POST)
            return render(request, \'login.html\', {\'msg\': msg, \'obj\': obj})
            #         if request.POST.get(\'auto_login\'):
            #             request.session.get_expiry(60*60*24*24)
            #         # request.session[\'is_login\'] = \'true\'
            #         # request.session[\'username\'] = data.get(\'username\')
            #         print(request.session[\'username\'])
            #         print(\'123\')
            #         return redirect(\'/\')
            #     else:
            #         errors[\'code\'] = \'请输入正确的验证码\'
            #         return render(request,\'login.html\',{\'obj\':obj,\'errors\':errors})
            # return render(request,\'login.html\',{\'obj\':obj})
login 用户登录

退出登录:

def logout(request):
    """
    用户退出登录
    :param request:
    :return:
    """
    try:
        # 删除is_login对应的value值
        del request.session[\'is_login\']
        del request.session[\'username\']
    except KeyError:
        pass
    return redirect(\'/login/\')
#验证码
logout(删除session里的值)

获取验证码:

#验证码
def check_code(request):
    """
    #读取硬盘中的文件,在页面显示
    # f = open(\'static/images/aa.png\',\'rb\')
    # data = f.read()
    # f.close()
    # return HttpResponse(data)
    #先写到本地,再读出到页面
    # 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([30,10],fill="red")
    #画线
    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)
    # code = \'\'.join(char_list)
    img.save(f,\'png\')
    data = f.getvalue()#读取内存里的值

    code = \'\'.join(char_list)
    print(request.session)#<django.contrib.sessions.backends.db.SessionStore object at 0x00000258DB88DC88>
    request.session[\'code\'] = code#保存在session里
    """
    from io import BytesIO
    from utils.random_check_code import rd_check_code
    stream = BytesIO()
    img, code = rd_check_code()
    img.save(stream, \'png\')
    # data = stream.getvalue()
    request.session[\'code\'] = code
    return HttpResponse(stream.getvalue())
check_code获取验证码

用户注册时上传头像: