且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django类基本视图中创建自定义方法

更新时间:2023-11-17 13:06:34

是的,这是CBV需要掌握的主要问题:当事情运行时,执行的顺序是什么(请参阅 https://ccbv.co.uk/.它看起来很复杂,但是实际上您只需要编写一些方法即可,只需在其中添加您自己的行为即可.

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.

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.