简体   繁体   中英

Passing parameters to a view in Django

In my urls.py I have set handler404 to CustomErrorView . CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives.

Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised?

Already tried-

  • handler404 = CustomErrorView(errorcode = 404)
    This causes an "Expected one positional argument, none given error."
  • handler404 = CustomErrorView(request, errorcode = 404)
    This causes a NameError ( Name 'request' is not defined )

My 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)

My views.py (after using the modifications recommended by @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

You can use a function closure to create the view function:

def create_error_view(error_code):
    def custom_error_view(request, *args, **kwargs):
        # You can access error_code here
    return custom_error_view

Then just call create_error_view to set the handler:

handler404 = create_error_view(error_code=404)

Or you can use functools.partial() , which basically does the same:

from functools import partial

handler404 = partial(custom_error_view, error_code=404)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM