create custom methods in django class base views

大憨熊 提交于 2021-02-05 05:15:26

问题


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:


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.



来源:https://stackoverflow.com/questions/35406930/create-custom-methods-in-django-class-base-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!