django搭建个人博客08,添加访问权限

来源:互联网 发布:godaddy创建数据库 编辑:程序博客网 时间:2024/05/18 11:48

为publish页面添加访问权限

1.修改www/urls.py

  a.在www应用的urls.py里添加django提供的一套验证框架
Authentication Views

vim www/urls.pyfrom django.conf.urls import includeurl('^',include('django.contrib.auth.urls')),

  b.在www/templates/registration下编写这套框架需要的html模板文件
html模板

e.g login.html<!-- login.html -->{% extends "www/www_base.html" %}{% block content %}{% if form.errors %}<p>Your username and password didn't match. Please try again.</p>{% endif %}{% if next %}    {% if user.is_authenticated %}        <p>Your account doesn't have access to this page. To proceed,            please login with an account that has access.</p>    {% else %}        <p>Please login to see this page.</p>    {% endif %}{% endif %}<form method="post" action="{% url 'www:login' %}">{% csrf_token %}    <table>        <tr>            <td>{{ form.username.label_tag }}</td>            <td>{{ form.username }}</td>        </tr>        <tr>            <td>{{ form.password.label_tag }}</td>            <td>{{ form.password }}</td>        </tr>    </table>    <input type="submit" value="login" />    <input type="hidden" name="next" value="{{ next }}" /></form>{# Assumes you setup the password_reset view in your URLconf #}<p><a href="{% url 'www:password_reset' %}">Lost password?</a></p>{% endblock %}<!-- end login.html -->

2.修改article/publish的view,使其需要staff权限

  a.仿照login_required的源码,写一个staff_required
login_required
User

vim www/auths.pyfrom functools import wrapsfrom django.conf import settingsfrom django.contrib.auth import REDIRECT_FIELD_NAMEfrom django.core.exceptions import PermissionDeniedfrom django.shortcuts import resolve_urlfrom django.utils.decorators import available_attrsfrom django.utils.six.moves.urllib.parse import urlparsefrom django.contrib.auth.decorators import user_passes_testdef staff_required(function=None,redirect_field_name=REDIRECT_FIELD_NAME,login_url=None):    actual_decorator=user_passes_test(        lambda u:u.is_staff,        login_url=login_url,        redirect_field_name=redirect_field_name    )    if function:        return actual_decorator(function)    return actual_decorator

  b.参照示例让ArticlePublishView继承Staff_test
Mixins that wrap as_view()

vim www/auths.pyclass Staff_test(object):    @classmethod    def as_view(cls,**initkwargs):        view=super(Staff_test,cls).as_view(**initkwargs)        return staff_required(view,login_url='www:login')  vim www/views.pyfrom .auths import *class ArticlePublishView(Staff_test,FormView):    ....

登录*/blogs/article/publish查看

authentication

0 0
原创粉丝点击