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

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

问题描述

假设我想创建一个基于类的视图,它更新创建一个对象.来自上一个问题我发现我可以做以下事情之一:

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) 使用 2 个通用视图 CreateViewUpdateView,我认为这意味着有两个 URL 指向两个不同的类.

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

2) 使用继承基本 View 的基于类的视图,我认为这意味着有两个 URL 只指向 1 个类(我创建的继承了 View).

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).

我有两个问题:

a) 哪个更好?

b) ccbv.co.uk 显示了一个基本的 View,但我没有看到任何记录的获取、发布等方法,这是正确的吗?

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

推荐答案

为什么需要通过一个 View 来处理创建和更新?拥有两个单独的视图要简单得多,每个视图都继承自其各自的通用视图类.如果您愿意,它们可以共享相同的表单和模板,而且它们很可能是从不同的 URL 提供的,因此我不知道将它们整合到一个视图中会得到什么.

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.

所以:使用两个视图,一个从 CreateView 继承,另一个从 UpdateView 继承.这些几乎可以处理您可能需要的一切,而第二种方法需要您自己重新发明轮子.如果您有一些在创建或更新对象时使用的通用内务管理"代码,则可以选择使用 mixin,或者您可以创建自己的视图来覆盖这两个用例,继承自 CreateViewUpdateView.

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天全站免登陆