23Django云笔记项目6(编写登录状态装饰器并完成文章发布)

一完成登录校验装饰器

1先把装饰器的架子搭起来:

外侧check_login接收的参数fn,其实是内侧的def warp(),因为内测的这个函数返回值就是fn

#装饰器架子固定写法:
def check_login(fn):
    def warp(request,*args,**kwargs):
        return fn(request,*args,**kwargs)
    return warp

2给装饰器架子添肉,完成登录状态装饰器的编写:

如果username和uid都不在session里,那么就从cookies里获取这两个值,如果这两个值还不存在就304跳转到登录页面,如果cookie里有这两个值就回写session

#校验登录状态装饰器:
def check_login(fn):
    def warp(request,*args,**kwargs):
        if 'username' not in request.session or 'uid' not in request.session:
            #检查cookies
            c_username = request.COOKIES.get('username')
            c_uid = request.COOKIES.get('uid')
            if not c_username or not c_uid:
                return HttpResponseRedirect('/user/login')
            else:
                #回写sessiom
                request.session['username'] = c_username
                request.session['uid'] = c_uid
        return fn(request,*args,**kwargs)
    return warp

二完成文章发布功能:

1创建应用:

D:\PycharmProjects\tyj_note>python manage.py startapp note

2注册应用:

INSTALLED_APPS = [
    'note',
]

3编写文章模板:

from user.models import User
class Note(models.Model):
    title = models.CharField('标题',max_length=100)
    content = models.TextField('内容')
    create_time = models.DateTimeField('创建时间',auto_now_add=True)
    update_time = models.DateTimeField('更新时间',auto_now=True)
    user = models.ForeignKey(User,on_delete=models.CASCADE)

4同步数据库:

D:\PycharmProjects\tyj_note>python manage.py makemigrations
D:\PycharmProjects\tyj_note>python manage.py migrate

5编写视图

def add_note(request):
    if request.method == 'GET':
        return render(request,'note/add_note.html')
    elif request.method == 'POST':
        return HttpResponse('添加笔记成功')

6在note应用下创建templates/note/add_note.html

<body>
<form action="/note/add" method="post">
    <p>
        标题:<input type="text" name="title"> <input type="submit" value="保存">
    </p>
    <p>
        <textarea cols="30" rows="10" name="content"></textarea>
    </p>
</form>
</body>

7完成路由分发并浏览http://127.0.0.1:8000/note/add

#主路由
 path('note/',include('note.urls')),
#子路由
from django.urls import path
from . import views
urlpatterns = [
    path('add',views.add_note)
]

8完善文章发布的视图函数

@check_login
def add_note(request):
    if request.method == 'GET':
        return render(request, 'note/add_note.html')
    elif request.method == 'POST':
        uid = request.session['uid']
        title = request.POST['title']
        content = request.POST['content']
        Note.objects.create(title=title,content=content,user_id=uid)
        return HttpResponse('添加笔记成功')

 

上一篇:设计模式--桥接模式】


下一篇:Python operator.itemgetter()