6

I want to use generic class base views using django 1.9 What i am trying to understand that

from django.views.generic import CreateView
from braces.views import LoginRequiredMixin
from .models import Invoice

class InvoiceCreateView(LoginRequiredMixin,CreateView):
    model = Invoice

    def generate_invoice(self):
        ...
        return invoice

now i want to bind this custom method to url. How can i achive this? I know using function base view its simple but i want to do this using class base views.

Help will be appreciated.

1
  • Its unclear what you're trying to achieve here, you can only respond to urls with a http request Commented Feb 15, 2016 at 10:45

1 Answer 1

7

Yes, this is the main issue to grasp in CBV: when things run, what is the order of execution (see http://lukeplant.me.uk/blog/posts/djangos-cbvs-were-a-mistake/).

In a nutshell, every class based view has an order of running things, each with it's own method.

CBV have a dedicated method for each step of execution.

You would call your custom method from the method that runs the step where you want to call your custom method from. If you, say, want to run your method after the view found that the form is valid, you do something like this:

Class InvoiceCreateView(LoginRequiredMixin,CreateView):
    model = Invoice

    def generate_invoice(self):
        ... do something with self.object
        return invoice

    def form_valid(self,form):

        self.object = form.save()
        self.generate_invoice()
        return super(InvoiceCreateView,self).form_valid(form)

So you have to decide where your custom method should run, and define your own method on top of the view generic method for this step.

How do you know what generic method is used for each step of executing the view? That the method the view calls when it gets the initial data for the form is def get_initial? From the django docs, and https://ccbv.co.uk/. It looks complex, but you actually have to write very few methods, just where you need to add your own behaviour.

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

9 Comments

In url is it not possible to call the generate_invoice() method directly?
Why? when do you want it to run?
In the url the CBV returns as_view(), which is callable function that gets a reuqest, docs.djangoproject.com/es/1.9/ref/class-based-views/base/…. From this entry point (actually the CBV dispatch method), the CBV runs all the steps.
consider i want to do some calculations and save partial data in other table. I wrote all this in generate_invoice() method.
So why would you run it in the url? The url just invokes the correct view. From this view, you go on.
|

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.