【问题标题】:Passing parameters to a view in Django将参数传递给Django中的视图
【发布时间】:2017-12-13 08:07:03
【问题描述】:

在我的urls.py 中,我已将handler404 设置为CustomErrorViewCustomErrorView 是一个通用视图,它根据收到的错误消息和错误代码生成错误模板。

由于 handler404 仅在出现 404 错误的情况下才会引发,我如何将 errorcode = 404 kwarg 发送到 CustomErrorView

已经试过了-

  • handler404 = CustomErrorView(errorcode = 404)
    这会导致“预期一个位置参数,没有给定错误”。
  • handler404 = CustomErrorView(request, errorcode = 404)
    这会导致 NameError (Name 'request' is not defined)

我的 urls.py:

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)

我的views.py(使用@knbk推荐的修改后):

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

【问题讨论】:

  • 如果需要我的任何代码来解决问题,请询问。
  • CustomErrorView 是 Django 的 View 的子类的基于类的视图吗?
  • @knbk No.. 这是一个基于函数的(普通)视图。
  • 用 urls.py 发表你的观点

标签: python django python-3.x django-views parameter-passing


【解决方案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)

【讨论】:

  • 现在我得到一些中间件错误:'function' object has no attribute 'get'
  • @PrithvishBaidya Traceback?
  • 无法获取回溯,因为错误页面仅在DEBUG = False时显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2017-07-07
  • 2012-01-17
  • 1970-01-01
  • 2018-01-08
相关资源
最近更新 更多