用于创建和更新的基于Django类的视图 [英] Django Class Based View for both Create and Update

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

问题描述

假设我想创建一个基于类的视图更新创建对象。从上一个问题我找出了我可以做以下一件事:



1)使用2个通用视图 CreateView UpdateView ,我认为这意味着有两个URL指向两个不同的类。



2)使用继承的基于类的视图基础查看,我认为这意味着有两个URL指向只有一个类(我创建了继承查看)。



我有两个问题:



a)哪个更好? p>

b) ccbv.co.uk 显示一个基础查看,但我看不到任何获取,发布等方法记录,这是正确的吗? / p>

解决方案

为什么需要处理create和up日期单一查看?有两个单独的视图要简单得多,每个视图都从相应的通用视图类继承。如果您愿意,他们可以共享相同的表单和模板,并且最有可能由不同的网址提供,所以我不会看到您将它变成一个视图。



所以:使用两个视图,一个继承自 CreateView ,另一个从 UpdateView 继承。这几乎可以处理您可能需要的一切,而第二种方法将需要您自己重新发明。如果在创建或更新对象时使用一些常见的内务代码的情况下,使用mixin的选项,或者您可以创建涵盖两种用例的自己的视图,从 CreateView UpdateView


Say I want to create a Class Based View which both updates and creates an object. From a previous question I worked out I could do one of the following things:

1) Use 2 generic views CreateView and UpdateView which I think would mean having two URL's pointing to two different classes.

2) Use a class based view which inherits base View, which I think would mean having two URL's pointing to just 1 class (I created which inherits View).

I have two questions:

a) Which is better?

b) ccbv.co.uk shows a base View, but I don't see any get, post etc methods documented, is this correct?

解决方案

Why do you need to handle both create and update by a single View? It's much simpler to have two separate views, each inheriting from its respective generic view class. They can share the same form and template if you wish, and they're most likely served from different URLs, so I don't see what would you get by making it into a single view.

So: use two views, one inheriting from CreateView and the other from UpdateView. These handle pretty much everything you might need, while the second approach would require you to reinvent the wheel yourself. If cases when you have some common "housekeeping" code that is used both when creating or updating objects, the option of using a mixin, or you can perhaps create your own view that covers both use cases, inheriting from both CreateView and UpdateView.

这篇关于用于创建和更新的基于Django类的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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