• Django之小结


    常用的函数方法与包的调用

    # 登陆视图函数
    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            user = request.POST.get('user')
            pwd = request.POST.get('pwd')
            validcode = request.POST.get('validcode')
            
            response = {'user':None,'err_msg':''}
            if validcode.upper() == requeset.session['keep_str'].upper():
                user_obj = auth.authenticate(username=user,password=pwd)
                if user_obj:
                    auth.login(request,user_obj)
                    response['user']=user
                else:
                    response['err_msg']='用户名或密码错误'
            else:
                response['err_msg']='验证码错误'
            from django.http import JsonResponse(response)
    
    # 注册视图函数
    def register(request):
        if request.is_ajax():
            res = {'user':None,'err_msg':''}
            form = UserForm(request.POST)
            if form.is_valid():
                res['user']=form.cleaned_data.get('user')
                user = form.cleaned_data.get('user')
                pwd = form.cleaned_data.get('pwd')
                email = form.cleaned_data.get('email')
                
                user = UserInfo.objects.create_user(username=user,password=pwd,email=email)
                            
            else:
                res['err_msg']=form.error
            return JsonResponse(res)
    
        else:
            form =UserForm()
            return render(request,'register.html',local())
    # 注销
    def logout(request):
        auth.logout(request)
        return redirect('/login/')
    # 修改密码
    def setpwd(request):
        if request.method =='GET':
            return render(request,'setpwd.html')
        else:
            response={'user':None,'err_msg':''}
            pwd = request.POST.get('pwd')
            rpwd = request.POST.get('rpwd')
            if pwd ==rpwd:
                user = UserInfo.objects.get(username=request.user.username)
                user.set_password(raw_password=pwd)
                user.save()
                response['user']=200
            else:
                response['err_msg']='两次输入不一致'
            return JsonResponse(response)
    
    # 主页
    def index(request):
        return render(request,'index.html')
    
    
    # django组件路径
    shortcuts:捷径   from django.shortcuts import render,HttpResponse,redriect
    http:传输        from django.http import JsonResponse
    contrib:附件     from django.contrib import auth    
    urls:路径        from django.urls import reverse
    models:模型      from django.models import Q
    
    
    
    # 登陆装饰器
    auth组件提供的装饰器
    导入方法: from django.auth.decorators import login_required
    此外还需要在setting中设置 认证路径 LOGIN_ULR='/longin/'
    
    # 静态文件
    1.创建静态文件包 static
    2.在setting中设置 static路径  
        STATIC_URL = '/static/'
        STATICFILES_DIRS = [
            os.path.join(BASE_DIR,'static')
    ]
    
    # 替换auth中的User表
    1.导入 from django.contrib.auth.models import AbstractUser
    2.在模型类中创建UserInfo表继承AbstractUser
    3.在setting中设置路径 AUTH_USER_MODEL=''
    
    # cbv
    导入View
    from django.views import View
    class CustomerView(View):
        def get(self,request):
            if reverse('customers_list') == request.path
                label='公户列表'
                customer_list = Customer.objects.filter(consultant__innull=Ture)
            else:
                label='我的客户'
                customer_list = Customer.objects.filter(consultant=request.user)
            
            # search
            val = request.GET.get('q')
            field = request.GET.get('field')
            if val:
                q = Q()
                q.chidren.append((field + '__contains',val))
                customer_list = customer_list.filter(q)
    
    # 添加与编辑
    基于cbv
    1.创建视图类 
    2.编写get与post方法
    from django.views import View
    class AddEditConsultRecordView(View):
        def get(self,request,edit_id=None):
            edit_obj = ConsultRecord.objects.filter(pk=edit_id).first()
            form = ConsultRecordModelForm(request,instance=edit_obj)
            return render(request, "add_edit_consultrecord.html", {"form": form,"edit_obj":edit_obj})
    
        def post(self,request,edit_id=None):
            edit_obj = ConsultRecord.objects.filter(pk=edit_id).first()
            form=ConsultRecordModelForm(request.POST,instance=edit_obj)
            if form.is_valid():
                form.save()
                return redirect(reverse("consult_records"))
            else:
                return render(request, "add_edit_consultrecord.html", {"form": form,"edit_obj":edit_obj})
        
    # 权限相关
    1.创建表关系,建立权限关系表
    2.编写视图函数与中间件
        视图函数:
            1.获取用户信息
            2.验证信息,成功设置session(request.session['user_id']=user.pk),
            3.查询表中用户拥有的权限 permissions = Role.objects.filter(user=user).values('permissions__url').distinct() #去重
            4.遍历permissions保存列表格式,保存到session中  requeset.session['premissios_list']=premissios_list
        中间件:
            1.获取到访问路径
            2.设置白名单的同时需要注意admin
            3.校验是否登陆过,判断session中有没有值,如果没有返回 登陆路径
            4.校验权限,判断session中有没有对应的权限
                for reg in premissions_list:
                    reg='^%s$' %reg
                    rul = re.search(reg,current_path)
                    if rul:
                        return Nnoe #放行
        
  • 相关阅读:
    mysql外键和连表操作
    数据库的操作
    进程之select和epoll
    jwt的应用生成token,redis做储存
    为什么前后端分离不利于seo
    redis的bitmap
    lnmp环境的nginx的tp5配置
    虚拟机安装cenos7后ifcfg看网卡无inet地址掩码等信息
    rsa加密
    hydra命令
  • 原文地址:https://www.cnblogs.com/qq631243523/p/9960635.html
Copyright © 2020-2023  润新知