2

I have a created a view class "class Demo", which has 3 functions

  1. def update_time()
  2. def get_context()
  3. def before_response()

urls.py : url(r'^demo/$', Demo.as_view(),name='demo_class'),

When i'll enter url /demo/ how will it determine which function to call from "class Demo" ?

4 Answers 4

4

Because Django’s URL resolver expects to send the request and associated arguments to a callable function, not a class, class-based views have an as_view() class method which serves as the callable entry point to your class. The as_view entry point creates an instance of your class and calls its dispatch() method. dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed if not.

just read the docs

Sign up to request clarification or add additional context in comments.

1 Comment

As i understand dispatch handles few common requests, like get,post,delete etc. but what about that other functions besides get,post,dispatch. like i mentioned before_response(), update_time() etc. how will dispatch determine when to call them, do we have to override dispatch for them ?
3

Basically class based views are recommended when you need to handle both get and post requests at one point. For example in get method of class Register, you can render the registration form and in its post method, you can handle the form submission. If its a get request it will automatically invoke the get() method in the class, same for post request. Also you can write any common code in the dispatch() method which will be invoked for every request.eg:

class Register(View):

    def dispatch(self, *args, **kwargs):
        '''
        common code here
        ''' 
        return super(Register, self).dispatch(*args, **kwargs)

    def get(self, request):
        registration_form     = RegistrationForm()
        return render(request, 'new.html', { 'form': registration_form  })

    def post(self, request):
        registration_form     = RegistrationForm(request.POST or None)
        if registration_form.is_valid():
            #save form
            return HttpResponseRedirect(reverse('success-show'))
        return render(request,new.html', { 'form': registration_form  })

8 Comments

but what about that other functions besides get,post,dispatch. like i mentioned one before_response(), update_time() etc. how will dispatch determine when to call them, do we have to override dispatch for them ?
you need to identify the request in the dispatch and redirect them to your methods, class based views are not meant to work like normal methods
dispatch() is inbuilt method of class view, so i'll have to override this, right ?
yes. you are right and I think you are misinterpreting class based views. they are not meant to group some view methods, they must be written to take care of only one purpose
I mean if you have, views for login, register, updateprofile in a file, class based view is not there to group all this view methods to one class. You must have one class for login, one class for register e.t.c.
|
0

For references you can check this website.

You need to subclass a class based views, and depending on that it will have one or another method. For example TemplateView renders a template you pass in the template_name attribute.

All class based views care about is that the attributes needed to work properly are setted. That is done via different methods. You can check the django's documentation for specifics.

For example, if you want to render a form in your template view, you will need to pass the form in the context, so you can override get_context_data() like:

def get_context_data(self, **kwargs):
    context = super(DemoClass, self).get_context_data(**kwargs)
    context['form'] = MyForm()
    return context

There are different methods to handle different things, like querysets, objects, etc. They are not complicated, but they are specific. If a class based view does not fit what you need, it may be easier to implement the functionality from a more general view (View, TemplateView) than forcing a more specific one to do things it is not intended for.

1 Comment

I want to know how to override dispatch() function so it can call the right method.
0

slightly change the url add numbers one to three in url and put the condition in your view. Ex.

 url(r'^abc/(?P<newid>.*)$', 'class_demo'),

so your url will be like abc/1 or abc/2 or abc/3

view

def class_demo(requests, newid):
    if newid==1:
          update_time()
    elif newid==2:
          get_context()

Comments

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.