对于那些碰巧看到这个问题的人,这就是我最终在 1.3 中所做的事情。这与我在 1.1 中的做法几乎相同(除了更冗长)。 (即如我问题中的链接中所述)
例如urls.py 中的相关行可能看起来像
...
# pass a default value of page = 1 for optional parameter page
url(r'^obj/list$', ObjListView.as_view(), {'page': 1}, name='obj_list'),
url(r'^obj/list/page(?P<page>[0-9]+)$', ObjListView.as_view(), name='obj_list'),
...
# both new and edit use the same class, but edit obviously needs an id for the object.
# i should probably just be using pk but whatever.
url(r'^obj/new$', ObjEditView.as_view(), name='obj_edit'),
url(r'^obj/edit/(?P<obj_id>[0-9]+)/$', ObjEditView.as_view(), name='obj_edit'),
在上面的 ObjEditView 类的情况下,我们可能会有这样的事情
class ObjEditView(UpdateView):
...
form_class = ObjForm
model=Obj
...
# this puts our obj in self.object
def get_object(self):
# if the obj exists, intialize our variables with values from the obj instance
# if it is a new obj, intialize accordingly
try:
obj = Obj.objects.get(id = self.kwargs['obj_id'])
except (KeyError, ObjectDoesNotExist):
obj = Obj()
return obj
作为我在上述 cmets 中向 Alasdair 提出的问题的必然结果,类中各种函数的执行顺序通常与它们在文档中的顺序相对应。即在 UpdateView get_object() 之前 get_initial()