2017-12-04 5 views
0

ジェネリックViewクラスをカスタムクラスに置き換えて、このクラスへの参照をユーザ認証が自動的に行うようにしようとしています。djangoがユーザ認証を検証するジェネリッククラスを作成する

ザ・ベース・クラス

class CustomView(View): 

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

サブクラス

クラス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 

答えて

1

あなたはビュークラスで__init__をオーバーライドするべきではありません。

ただし、これを行う必要はありません。 DjangoにはすでにLoginRequired mixinが含まれています。

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と呼ばれます。

関連する問題