2016-05-31 7 views
0

ここでは非常に最初の質問です。外部メソッド(Django、views.py)から呼び出すときには "return render"を呼び出すことはできません

私のviews.pyファイルでユーザー認証を処理するために再利用可能なメソッドを作成する際に問題があります。今、私は別の方法としてそれを持っていること、それを

from django.shortcuts import render 
from django.contrib.auth.forms import AuthenticationForm 

def check_log_in(request): 
    username = None 
    if request.user.is_authenticated(): 
     user = request.user 
     if user.is_staff == False: 
      message = "You are not an authorized staff member." 
      form = AuthenticationForm() 
      context = {'form': form, 
         'message': message} 
      return render(request, 'obits/login.html', context) 
    else: 
     message = "Please log-in to add a new record." 
     form = AuthenticationForm() 
     context = {'form': form, 
        'message': message} 
     return render(request, 'obits/login.html', context) 

私は私の意見に直接この同じコードを配置する場合、それはうまく動作しますが、私が作成し、このようになりますutils.pyファイルをインポートしましたリターンレンダリングで折れず、代わりにコードを続けます。私はprintステートメントを使って、それが正しく呼び出されていることをテストしました。ここでは、現在のビューである:この現在のセットアップで

def new(request): 
    check_log_in(request) 

    if request.method == 'POST': 
     if form.is_valid(): 
      #code, yada, yada, context 
      return render(request, 'obits/detail.html', context) 
     else: 
      #code, yada, yada, context 
      return render(request, 'obits/new.html', context) 
    else: 
     #code, yada, yada, context 
     return render(request, 'obits/new.html', context) 

が、それはユーザーがログインしていないことを検出しますが、それでもちょうど先に行くとnew.htmlページを表示するのではなく、へのリダイレクトログイン。しかし、check_log_inに含まれている正確なコードを切り取って貼り付けるのではなく、うまく動作します。

アイデア?前もって感謝します!

+2

Jieterの答えが正しいですが、これは本当に物事の良い方法ではありません注意してください。 Djangoには 'login_required'デコレータがあります。ユーザーがログインしていない場合は、ログインフォームの表示と検証を担当する別のビューにリダイレクトされます。それははるかに良いパターンです。 –

答えて

2

check_log_in()から戻っても返された値で何もしない場合、new()ビューの実行は続行されます。

あなたはcheck_log_in()が何かを返したかどうかを確認する必要があり、それがなかった場合は、お使いのnew()ビューからそのを返す:

def new(request): 
    response = check_log_in(request) 
    if response is not None: 
     return response 

    if request.method == 'POST': 
     # rest of your code 
関連する問題