django创建泛型类以验证用户身份验证

时间:2017-12-04 21:01:19

标签: python django authentication generics constructor

我正在尝试用自定义类替换通用View类,以便在我引用此类时自动进行用户身份验证。

基类

class CustomView(View):

    def __init__(self, request):
        if not request.user.is_authenticated:
            redirect('register.registerForm')

子类

class DashboardPage(CustomView):

def get(self, request):
    user_object = User.objects.get(username=request.user)
    all_files = user_object.files_set.all()
    return render(request, 'dashboard/dashboard.html', {'all_files': all_files})

我希望在调用CustomView类时自动进行用户身份验证。并且还想知道这是否是为我的应用程序中需要身份验证的所有页面推广用户身份验证的最佳方法。

我收到以下错误:

TypeError at /dashboard/
__init__() missing 1 required positional argument: 'request'
Request Method: GET
Request URL:    http://127.0.0.1:8000/dashboard/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:    
__init__() missing 1 required positional argument: 'request'
Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62
Python Executable:  C:\Program Files (x86)\Python36-32\python.exe
Python Version: 3.6.3
Python Path:    
['C:\\Users\\Varun\\Desktop\\newsite',
 'C:\\Program Files (x86)\\Python36-32\\python36.zip',
 'C:\\Program Files (x86)\\Python36-32\\DLLs',
 'C:\\Program Files (x86)\\Python36-32\\lib',
 'C:\\Program Files (x86)\\Python36-32',
 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:    Mon, 4 Dec 2017 20:43:12 +0000

2 个答案:

答案 0 :(得分:1)

您不应在视图类中覆盖__init__

但是,没有必要这样做。 Django已经包含一个LoginRequired mixin,它可以完全满足您的需求。

答案 1 :(得分:1)

您需要使用LoginRequired mixin

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

如果用户未登录,则会自动重定向到表单域redirect_to的内容。在default login form view中,此字段称为next