Django个人博客搭建教程---自带登录登出及装饰器详解

一、urls.py

from django.conf.urls import url,include
from paper import views
from rest_framework import routers
from django.views.decorators.csrf import csrf_exempt

app_name = 'paper'

urlpatterns = [
    url('^$', views.PaperIndex.as_view(), name='index'),
    url(r'^login/$', views.paper_login, name='login'),
    url(r'^logout/$', views.paper_logout, name='logout'),
    url(r'^forgot/$', views.paper_forgot, name='forgot'),
]




二、views.py

from django.shortcuts import render
from django.http.response import HttpResponse, HttpResponseBadRequest,HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from django.utils.decorators import method_decorator



@method_decorator(login_required, name='dispatch')
class PaperIndex(View):

    def get(self, request):
        context = {

        }
        return render(request, 'paper_index.html', context=context)


@csrf_exempt
def paper_login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user:
            login(request, user)
            # return render(request, 'paper_index.html')
            return redirect('/paper/')
        else:
            return render(request, 'login.html', {
                'login_err': 'Please recheck your username or password !'
            })
    return render(request, 'login.html')


def paper_forgot(request):
    return render(request, 'forgot.html')


def paper_logout(request):
    logout(request)
    return render(request, 'login.html')


def paper_register(request):
    return render(request, 'register.html')
# Create your views here.

三、settings.py

LOGIN_URL = '/paper/login'
# 如果这里直接写login,则当装饰器重定向的时候会重定向到/accounts/login?next=
LOGOUT_URL = 'logout'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值