简体   繁体   English

有没有办法组合CreateView和UpdateView?

[英]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")

The other "double purpose" view solution that @AviahLaor mentions is to combine the CreateView and UpdateView in one view. @AviahLaor提到的另一个“双用途”视图解决方案是在一个视图中组合CreateViewUpdateView In my opinion, it is DRYer. 在我看来,这是DRYer。 The solution is given here very well. 这里给出解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法让updateview中的时间与django中createview中的时间保持一致 - is there a way to keep the time in updateview same as the time in createview in django 在CreateView上需要表单域的正确Django方法,而在UpdateView上是可选的? - The proper Django way to make a form field required on CreateView, but optional on UpdateView? CreateView不在提交时保存,而是在UpdateView上保存 - CreateView not saving on submit, but is on UpdateView django泛型CreateView和UpdateView中的Modelformset - Modelformset in django generic CreateView and UpdateView 有没有办法在Django中组合一个将对象信息传递给url和CreateView的函数? - Is there a way to combine a function that passes object information to a url and CreateView in Django? UpdateView和CreateView-代码有效还是可以改进? - UpdateView and CreateView - Is the code efficient or could improved on? 如何在Django中为CreateView和UpdateView创建通用模板 - How To Create Generic Templates for CreateView and UpdateView in Django 如何在Django CreateView和UpdateView中呈现Form实例? - How to render Form instance in Django CreateView & UpdateView? Django 在 CreateView 和 UpdateView 中调用自定义管理器方法 - Django call custom manager method in CreateView and UpdateView 有什么方法可以在CreateView表单中创建隐藏的表单字段? - Is any way to create hidden form field in CreateView form?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM