在Django类基本视图中创建自定义方法 [英] create custom methods in django class base views

查看:83
本文介绍了在Django类基本视图中创建自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用django 1.9使用通用类的基本视图我想了解的是什么

从django.views.generic导入

 导入CreateView从braces.views导入LoginRequiredMixin从.models导入发票类InvoiceCreateView(LoginRequiredMixin,CreateView):型号=发票def generate_invoice():...退货发票 

现在我想将此自定义方法绑定到url.我怎样才能做到这一点?我知道使用函数基础视图很简单,但是我想使用类基础视图来做到这一点.

我们将不胜感激.

解决方案

是的,这是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.

这篇关于在Django类基本视图中创建自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆