2

In a class based view, HTTP methods map to class method names. Below, defined a handler for GET requests with the get method and url called get method. My question is how did the url map to the get method?

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

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Hello, World")
2
  • did you mean MyView.as_view() instead of TestView.as_view()? Commented Dec 2, 2016 at 5:45
  • yes, I edited code Commented Dec 2, 2016 at 5:55

2 Answers 2

3

The url doesn't map to the get method, it maps to the view. Its up to the request method to guide django in the right way.

If you're talking in terms of actual code, its the dispatch method on the view.

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)
Sign up to request clarification or add additional context in comments.

3 Comments

how do I make the url(r'^hello-world/$', MyView.as_view(), name='hello_world') call a PUT rather than a GET?
@semanticui - if you have a new question, then you should ask it as a new question. If one of these answers helped solve this, you should consider accepting it
I'm making new question @Sayse, please chip in.
2

Why not have a look at the code.

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

You will see the as_view() method (which gets called in your urls.py) has at line 67:

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

The dispatch() method in turn calls get in line 85 (assuming it is a GET request):

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

2 Comments

how do I make the url(r'^hello-world/$', MyView.as_view(), name='hello_world') call a PUT rather than a GET?
You want the html form that is sending data to the view to have 'method ="PUT" '. Have a look at the update view, as that probably covers it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.