我想在我正在开发的网站上实现以下功能:
1. User 'flags' object by clicking on object specific link.
2. Link leads user to confirmation page.
3. If the user confirms, then a property of the object is changed.
4. User is returned to the original page he/she flagged the object from.
该功能的操作方式与 django 的删除 View 类似,只不过不是删除对象,而是更改对象的字段。或者,该函数类似于 UpdateView,但没有在服务器端代码中为用户交互的对象实现的表单和定义的字段更改。
哪种基于 django 类的 View 组合可以最优雅地实现此功能?
现在,我认为覆盖 UpdateView 的某些部分是最好的方法,我会在这方面取得进展时进行更新,但我认为其他人可能已经知道如何实现此类功能.
更新: 目前,正在实现一些看起来
class NoFormUpdateView(SingleObjectTemplateResponseMixin, BaseDetailView):
template_name_suffix = '_no_form_update'
def update_fields(self, request, *args, **kwargs):
"""
Modifies object fields thenredirects to the success URL.
"""
self.object = self.get_object()
success_url = self.get_success_url()
#Do stuff
if success:
return HttpResponseRedirect(success_url)
else:
return SomethingWentWrong
def post(self, request, *args, **kwargs):
return self.update_fields(request, *args, **kwargs)
def get_success_url(self):
if self.success_url:
return self.success_url % self.object.__dict__
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
最佳答案
我不同意你不使用FormView的方法。确认实际上是一个表单(即使它只有一个确认按钮)——不是一个ModelForm
,而是一个普通的django表单来确认您的选择。
我建议做的是继承 FormView
并添加一个 SingleObjectMixin
。像这样的东西(这是来 self 在另一个项目中实现的 Cancel 方法,但你会明白的):
class CancelFormView(FormView, SingleObjectMixin): queryset = models.Process.all() form_class = forms.YesNoForm template_name = 'cancel.html' def form_valid(self, form): obj = self.get_object() yesno = form.cleaned_data['yesno'] if yesno=='YES': # Do something with the object # the update_fields method you define should be a method of your object obj.cancel() messages.info(self.request, u"Cancel ok!") else: messages.info(self.request, u"Cancel aborted!") return HttpResponseRedirect(reverse("process_view", args=[obj.id] ))
如您所见,您只需重写类的 form_valid
方法并定义 queryset
、form_class
和 template_name
属性。然后,如果用户确实确认他想要它(他在表单中选择了"is"),那么您只需更新您的字段(或执行您喜欢的任何其他操作)。我相信这是实现您的要求的最干燥的方式。
关于python - 我应该使用哪些类来修改没有使用 Django 表单和 UpdateView 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736575/