在通用FormView中,文档说成功后,它会重定向到success_url
属性。
如果我碰巧有UpdateView
,并像这样重写form_valid
:
class PreferenceUpdateView(LoginRequiredMixin, UpdateView):
form_class = ProfileUpdateForm
model = Profile
template_name = 'profile.html'
def form_valid(self, form):
return super(PreferenceUpdateView, self).form_valid(form)
只返回super(PreferenceUpdateView, self).form_valid(form)
而非return HttpResponseRedirect(self.get_success_url())
,视图如何知道重定向到哪里?
什么时候我应该什么时候不必指定重定向?
答案 0 :(得分:1)
扩展链接是:
FormMixin->ModelFormMixin->BaseUpdateView->UpdateView
然后super(PreferenceUpdateView, self).form_valid(form)
将调用form_valid
中的FormMixin
,其源代码为:
def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url
def form_valid(self, form):
"""
If the form is valid, redirect to the supplied URL.
"""
return HttpResponseRedirect(self.get_success_url())
如果您想指定重定向,请覆盖success_url
类中的PreferenceUpdateView
,如:
from django.core.urlresolvers import reverse_lazy
class PreferenceUpdateView(LoginRequiredMixin, UpdateView):
success_url = reverse_lazy('preference_list')
或覆盖get_success_url
方法:
def get_success_url(self):
"""
Returns the supplied success URL.
"""
return reverse_lazy('preference_list')
如果您希望您的success_url根据实例进行更改:
def form_valid(self, form):
instance = form.save()
self.success_url = reverse('preference_detail', kwargs={'pk': instance.id})
return super(PreferenceUpdateView, self).form_valid(form)