The Class Based "View"

People often find working with class based views hard, but they are simple... Once you spend time figuring them out. In this video start with the base of building blocks and work your way through completly understanding the base View of (generic) class based views.

resources

command line

curl -i http://localhost:8000/ -X GET
curl -i http://localhost:8000/ -X POST
curl -i http://localhost:8000/ -X OPTIONS

home/views.py

from django.http import HttpResponse, HttpResponseNotAllowed

from django.views.generic import View


class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        print request.method
        print self.http_method_names
        print self._allowed_methods()
        return super(BaseView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello World I am a get')

    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello world I am a post')

def view(request):
    http_method_names = [
        'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    if request.method == 'OPTIONS':
         response = HttpResponse()
         response['Allow'] = ', '.join(http_method_names)
         response['Content-Length'] = '0'
         return response

    # Checks if we are going to allow usage of these methods
    if request.method.lower() in http_method_names:
        if request.method == 'GET':
            return HttpResponse('all the things')
        elif request.method == 'POST':
            return HttpResponse('for all the people')

    # Tell requester the method is not allowed, and lists what is allowed
    return HttpResponseNotAllowed(http_method_names)
comments powered by Disqus