在我的urls.py
我已将handler404
设为CustomErrorView
。 CustomErrorView
是一个通用视图,它根据错误消息和错误代码生成错误模板。
由于handler404
仅在出现404错误的情况下被提出,因此如果errorcode = 404
kwarg被提升,我怎样才能将CustomErrorView
kwarg发送给handler404 = CustomErrorView(errorcode = 404)
?
已经尝试过 -
handler404 = CustomErrorView(request, errorcode = 404)
Name 'request' is not defined
from django.conf.urls import url, include
from django.contrib import admin
from blog_user.views import home, create_error_view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home),
url(r'^', include('user_manager.urls')),
]
handler404 = create_error_view(error = 404)
handler500 = create_error_view(error = 500)
)我的urls.py:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
def create_error_view(error = 404, mybad = False):
def custom_error_view(request, error, mybad):
''' Returns a generic error page. Not completed yet. error code and messages are supposed to be modular so that it can be used anywhere for any error in the page.'''
content = "Incorrect url"
context= {
'error': error,
'content':content,
'mybad':mybad
}
response = render(request, 'error.html', context=context, status=error)
return HttpResponse(response)
return custom_error_view
我的views.py(使用@knbk推荐的修改后):
using (StreamReader sr = new StreamReader(@"D:\Templates\NewGridTemplate.txt"))
{
// Read the stream to a string, and write the string to the console.
obj.sGridTemplate = sr.ReadToEnd().Replace(Environment.NewLine, " ");
//Console.WriteLine(line);
}
return View(obj);
答案 0 :(得分:1)
您可以使用函数闭包来创建视图函数:
def create_error_view(error_code):
def custom_error_view(request, *args, **kwargs):
# You can access error_code here
return custom_error_view
然后只需调用create_error_view
来设置处理程序:
handler404 = create_error_view(error_code=404)
或者你可以使用functools.partial()
,基本上也是这样:
from functools import partial
handler404 = partial(custom_error_view, error_code=404)