Django:如果模型字段是特定值,则从页面重定向
Django: redirect from page if model field is certain value
我有一个基于 Class 的视图,可将用户发送到网页以查看项目。用户可以单击编辑按钮来编辑页面,但是,我不希望用户始终能够编辑页面。一旦模型中的字段 ('status') 设置为 'completed',我希望用户无法再更新页面。我有一个基于 class 的视图。如果状态=已完成,我如何将用户重定向到不同的 url,(例如视图 url)?我目前的方法是有一个表单,如果字段状态设置为已完成,则会出错。这并不理想,因为人们仍然可以看到编辑内容,并且可能想知道为什么它会出错。
urls.py
url(r'^update/(?P<status_id>[0-9A-Za-z]+)/$', ThingUpdateView.as_view(), name='update'),
class 基于视图
class ThingUpdateView(LoginRequiredMixin, UpdateView):
model = Thing
form_class = ThingChangeForm
template_name = 'thing/thing_update.html'
尝试覆盖 render_to_response
方法来处理 GET
请求和 form_valid
来处理 POST
和 PUT
:
from django.shortcuts import redirect
class ThingUpdateView(LoginRequiredMixin, UpdateView):
model = Thing
form_class = ThingChangeForm
template_name = 'thing/thing_update.html'
def render_to_response(self, context, **response_kwargs):
if self.object.status == 'completed':
return redirect('some-view-name')
return super().render_to_response(context, **response_kwargs)
def form_valid(self, form):
if self.object.status == 'completed':
return redirect('some-view-name')
return super().form_valid(form)
一种方法是使用 Javascript 来达到此目的。将表单元素的值设置为 "completed" 和 运行 JS 函数 window.location() 以重定向用户,如果该值设置为 "completed".
我有一个基于 Class 的视图,可将用户发送到网页以查看项目。用户可以单击编辑按钮来编辑页面,但是,我不希望用户始终能够编辑页面。一旦模型中的字段 ('status') 设置为 'completed',我希望用户无法再更新页面。我有一个基于 class 的视图。如果状态=已完成,我如何将用户重定向到不同的 url,(例如视图 url)?我目前的方法是有一个表单,如果字段状态设置为已完成,则会出错。这并不理想,因为人们仍然可以看到编辑内容,并且可能想知道为什么它会出错。
urls.py
url(r'^update/(?P<status_id>[0-9A-Za-z]+)/$', ThingUpdateView.as_view(), name='update'),
class 基于视图
class ThingUpdateView(LoginRequiredMixin, UpdateView):
model = Thing
form_class = ThingChangeForm
template_name = 'thing/thing_update.html'
尝试覆盖 render_to_response
方法来处理 GET
请求和 form_valid
来处理 POST
和 PUT
:
from django.shortcuts import redirect
class ThingUpdateView(LoginRequiredMixin, UpdateView):
model = Thing
form_class = ThingChangeForm
template_name = 'thing/thing_update.html'
def render_to_response(self, context, **response_kwargs):
if self.object.status == 'completed':
return redirect('some-view-name')
return super().render_to_response(context, **response_kwargs)
def form_valid(self, form):
if self.object.status == 'completed':
return redirect('some-view-name')
return super().form_valid(form)
一种方法是使用 Javascript 来达到此目的。将表单元素的值设置为 "completed" 和 运行 JS 函数 window.location() 以重定向用户,如果该值设置为 "completed".