[英]Is there any way to combine CreateView and UpdateView?
I want to show the form present in CreateView
if there was no item exists inside a model. 如果模型中没有项目,我想显示CreateView
的表单。 Else I need to show the form exists in the UpdateView
. 否则,我需要在UpdateView
显示该表单。 So that it would load the already saved values. 这样它就会加载已保存的值。 Later I should save the data to db by calling update_or_create
method. 稍后我应该通过调用update_or_create
方法将数据保存到db。
Is this possible? 这可能吗?
Instead of messing with a double purpose view, which is not trivial to find out which and when to run the correct method (and not recommended), add a third view that will redirect to CreateView or EditView. 而不是弄乱双重目的视图,这不是简单的找出哪个以及何时运行正确的方法(并且不推荐),添加第三个视图,将重定向到CreateView或EditView。
It should look something like this: 它应该看起来像这样:
from django.core.urlresolvers import reverse
class AddItemView(generic.CreateView):
...
class EditItemView(generic.EditView):
...
class UpdateItemRedirectView(generic.RedirectView):
def get_redirect_url(self):
if Item.objects.get( ...criteria... ).exists():
return reverse("url_name_of_edit_view")
else:
return reverse("url_name_of_add_view")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.