2009-11-28 4 views
7

私は認証されたDjangoのWebサイトに対してカスタムのハンドブック404を作成して、情報漏えいを防いでいます。Djangoのカスタムハンドラ404は404を示していますが、ヘッダ200を与えます

def check_logged_in_404(request): 
    """ Custom 404. Show friendly 404 when logged in and redirect to /login 
    when not logged in. 
    """ 
    if request.user.is_authenticated(): 
     return render_to_response('404.html') 
    else: 
     return HttpResponseRedirect('/login') 

機能的には、私が欲しいものを機能させます。しかし、404の戻りページのステータスは200で、正しいコード単位です。しかし、これは明らかに404の返品ステータスである必要があります。

raise404は無限再帰で終了しないと、ここに戻り、同じ問題が発生するため、raise404は機能しません。

私はHttpResponseNotFoundを試しましたが、これはDRY-ishではないテンプレートではなく引数として文字列を受け取ります。

そして、私は手動でヘッダーを設定しようとしました:

response = render_to_response('404.html') 
    response['Status'] = "Not Found - 404" 
    return response 

そして、ステータスヘッダは、実際に設定されていますが、ブラウザはまだ私はオプションの外だ200

を示して...誰それがヒントを持って、...私のヒーローにしてください:)

ありがとうとよろしく、

ジェラルド。

編集:私はすべての並べ替えところでにおけるステータスフィールドの値を試してみましたが、運:(

+0

あなたは、これはうーん "render_to_string" について認識していなかった私を – dirk

答えて

20

は私がrender_to_stringHttpResponseNotFoundを、使用していないと思います例えばreturn HttpResponseNotFound(render_to_string('404.html'))

+0

ビットいかに難しい信じられません。設定されたステータスコードが尊重されない理由についてはまだ不思議です。 とにかく...あなたは間違いなく「誰かのヒーロー」バッジを得ました。 – GerardJP

12

やっと見つけ理由を返された状態を。 。コードのdidntの仕事の代わりにヘッダーメッセージを設定するが、それは単にある:

それでも
response.status_code = 404 

、PiotrLegnicaによって提案されたコードは間違いなく、シンプルにreadabi勝バッジはまだ立って.. lityと美しさ;)

よろしく、

ジェラルド。

2

Http404の例外を使用してみませんか?

if request.user.is_authenticated(): 
    raise Http404 
else: 
    return HttpResponseRedirect('/login') 

これはちょうど良いことです。

+0

どうか私はHttp404を上げるとき500の応答でエンディングする。それにもかかわらず、関数内で区別が必要な場合は、再帰エラーで終了するか、page_not_found()ビューを作成する必要があります。とにかくThanx。 – GerardJP

+0

django.httpからHttp404をインポートしましたか? – gruszczy

+0

Emphh、それを上げると404ハンドラにリダイレクトされます。何人かの人々はそれらを習慣にしたい。 – DataGreed

1

以下の例のようにすることができます。アプリケーションのurls.pyの中へ

追加:

アプリケーションのviews.pyアドオンの中へ
# Imports 
from django.conf.urls.static import static 
from django.conf.urls import handler404 
from django.conf.urls import patterns, include, url 
from yourapplication import views 

## 
# Handles the URLS calls 
urlpatterns = patterns('', 
    # url(r'^$', include('app.homepage.urls')), 
) 

handler404 = views.error404 

:状態= 404

希望:

# Imports 
from django.shortcuts import render 
from django.http import HttpResponse 
from django.template import Context, loader 


## 
# Handle 404 Errors 
# @param request WSGIRequest list with all HTTP Request 
def error404(request): 

    # 1. Load models for this view 
    #from idgsupply.models import My404Method 

    # 2. Generate Content for this view 
    template = loader.get_template('404.htm') 
    context = Context({ 
     'message': 'All: %s' % request, 
     }) 

    # 3. Return Template for this view + Data 
    return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404) 

秘密は最後の行にありますそれは助け!

私は、このアプローチのコミュニティへのインプットを楽しみにしています。上記の提案に基づき=)

7

は、ここ404、500ハンドラの私の短いバージョンは次のとおりです。

def handler404(request): 
    response = render_to_response('404.html', {}, 
            context_instance=RequestContext(request)) 
    response.status_code = 404 
    return response 


def handler500(request): 
    response = render_to_response('500.html', {}, 
            context_instance=RequestContext(request)) 
    response.status_code = 500 
    return response 
+0

この回答は最も簡単に実装でき、cusotm urls.pyの設定は必要ありません。 –

1

あなたはrenderメソッドを使用することができます

from django.shortcuts import render 

を持つコンテンツであるのHttpResponseを返します。 の結果で満たされ、django.template.loader.render_to_string()には 引数が渡されます。

デフォルトでRequestContextを使用します。

例:

return render(request, '404.html', status=404) 

やキーワードで:

return render(request, '404.html', {'data': 'some data'}, status=404) 
関連する問題