django 用户登录

django已经做好用户登录及权限相关的功能,我们只需要使用就可以了。

https://docs.djangoproject.com/zh-hans/2.2/topics/auth/default/

login页面

<form action="/backend/login-in" method="post">
        {% csrf_token %}
        <div class="input-group mb-3">
          <input type="text" name="login" class="form-control" placeholder="用户名">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-user"></span>
            </div>
          </div>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="secret" class="form-control" placeholder="密码">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div>
        <div class="row">
            <button type="submit" class="btn btn-primary btn-block">Sign In</button>
        </div>
      </form>

view

from django.shortcuts import redirect
from django.views.generic.base import View, TemplateView
from django.contrib.auth import authenticate, login, logout

class LoginView(TemplateView):
    template_name = 'site/login.html'


class LoginInView(View):
    def post(self, request, *args, **kwargs):
        username = request.POST.get('login')
        password = request.POST.get('secret')
        user = authenticate(request, username=username, password=password)
        print(user)
        if user is not None:
            login(request, user)
            return redirect('/backend/config/index')
        else:
            return redirect('/backend/login')

class LoginOutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return redirect('/backend/login')

url

path('login', LoginView.as_view(), name = 'login'),
path('login-in', LoginInView.as_view(), name = 'login-in'),
path('login-out', LoginOutView.as_view(), name = 'login-out'),

 

页面登录验证

由于我自定义了登录页面,所以需要覆盖默认跳转登录页面。


from django.contrib.auth.mixins import LoginRequiredMixin

class BackendLoginRequiredMinix(LoginRequiredMixin):
    login_url = '/backend/login'
    redirect_field_name = 'redirect_to'

使用

from backend.helps.BackendLoginRequiredMinix import BackendLoginRequiredMinix

class AdvPositionIndexView(BackendLoginRequiredMinix, ListView):
    model = AdvPosition # 指定模型
    context_object_name = 'grid' # 默认object_list
    paginate_by = 2 # 每页显示数量 默认Paginator实例 page_obj
    ordering = ['-id'] # 默认排序
    template_name = 'adv-position/index.html'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值