2016-12-02 101 views
1

在基于类的视图中,HTTP方法映射到类方法名称。下面,使用名为get方法的get方法和url定义GET请求的处理程序。我的问题是如何将url映射到get方法?Django如何将url映射到基于类的视图函数?

url(r'^hello-world/$', MyView.as_view(), name='hello_world'), 

class MyView(View): 
    def get(self, request, *args, **kwargs): 
     return HttpResponse("Hello, World") 
+0

你的意思是MyView.as_view()而不是TestView.as_view()? –

+0

是的,我编辑代码 – SemanticUI

回答

3

的网址地图get方法,它映射到视图。它的请求方法以正确的方式引导django。

如果你正在谈论实际的代码,它在视图上的dispatch方法。

def dispatch(self, request, *args, **kwargs): 
    # Try to dispatch to the right method; if a method doesn't exist, 
    # defer to the error handler. Also defer to the error handler if the 
    # request method isn't on the approved list. 
    if request.method.lower() in self.http_method_names: 
     handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 
    else: 
     handler = self.http_method_not_allowed 
    return handler(request, *args, **kwargs) 
+0

如何使url(r'^ hello-world/$',MyView.as_view(),name ='hello_world')调用PUT而不是GET? – SemanticUI

+0

@semanticui - 如果你有一个新的问题,那么你应该问它作为一个新的问题。如果其中一个答案帮助解决了这个问题,您应该考虑接受它 – Sayse

+0

我正在提出新问题@Sayse,请切入。 – SemanticUI

2

为什么不看看代码。

http://ccbv.co.uk/projects/Django/1.10/django.views.generic.base/View/

您将看到as_view()方法(该方法被调用在你的urls.py)在第67行:

return self.dispatch(request, *args, **kwargs) 

分派()依次调用方法得到线85(假设它是一个GET请求):

if request.method.lower() in self.http_method_names: 
    handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 
+0

如何使网址(r'^ hello-world/$',MyView.as_view( ),name ='hello_world')调用PUT而不是GET? – SemanticUI

+0

你想要发送数据到视图的html表单具有'method =“PUT”'。看看更新视图,因为这可能涵盖它。 –