3 回答

TA貢獻1840條經(jīng)驗 獲得超5個贊
請不要替換中間件或做一些其他奇怪的事情。非常簡單:DisallowedHost() 由調用get_host()請求對象的第一個事物引發(fā)。通常,這是一個中間件,因為在請求/響應周期中過早執(zhí)行它會導致無法關閉或自定義。
因此,首先將您的自定義中間件注入鏈中并短路那里的東西:
# File: main.middleware
from django.shortcuts import redirect
from django.core.exceptions import DisallowedHost
class FriendlyDisallowedHost:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
try:
checkhost = request.get_host()
except DisallowedHost:
return redirect("http://localhost/")
return self.get_response(request)
設置:
MIDDLEWARE = [
"main.middleware.FriendlyDisallowedHost",
# ... rest of middleware
]

TA貢獻1804條經(jīng)驗 獲得超7個贊
因為 Django 將在調用您的視圖之前攔截請求并引發(fā)此異常,所以您應該使用自定義錯誤視圖來覆蓋默認錯誤視圖來處理此類錯誤
在您的應用程序視圖中,編寫您想要處理的處理程序DisallowedHost
from django.views.defaults import bad_request as default_bad_request
from django.core.exceptions import DisallowedHost
from django.http import HttpResponse
def my_bad_request_handler(request, exception=None, **kwargs):
? ? if isinstance(exception, DisallowedHost):
? ? ? ? return HttpResponse("This server is not configured for this hostname", status=400)
? ? # if it's some other kind of bad request, use Django's default handler
? ? return default_bad_request(request, exception, **kwargs)
然后在 URLConf 中將 400 處理程序設置為您的自定義視圖:
handler400 = 'mysite.views.my_bad_request_handler'

TA貢獻2080條經(jīng)驗 獲得超4個贊
您可以為此使用自定義中間件。
為此,通過子類化CommonMiddleware
--(Doc)類并重寫process_request(...)
--(Doc)方法來創(chuàng)建自定義中間件
# some_place/some_module.py
from django.middleware.common import CommonMiddleware
from django.core.exceptions import DisallowedHost
from django.http.response import HttpResponse
from django.shortcuts import render
class CustomCommonMiddleware(CommonMiddleware):
? ? def process_request(self, request):
? ? ? ? try:
? ? ? ? ? ? return super().process_request(request)
? ? ? ? except DisallowedHost:
? ? ? ? ? ? return render(request, 'something.html')
然后,將中間件替換為-(Doc)設置django.middleware.common.CommonMiddleware
中新創(chuàng)建的自定義類,如下所示:MIDDLEWARE
# some_place/some_module.py
from django.middleware.common import CommonMiddleware
from django.core.exceptions import DisallowedHost
from django.http.response import HttpResponse
from django.shortcuts import render
class CustomCommonMiddleware(CommonMiddleware):
? ? def process_request(self, request):
? ? ? ? try:
? ? ? ? ? ? return super().process_request(request)
? ? ? ? except DisallowedHost:
? ? ? ? ? ? return render(request, 'something.html')
添加回答
舉報