重定向到详细信息视图

重定向到详细信息视图

本文介绍了Django:创建后重定向到详细信息视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

成功提交表单并创建对象后,我想重定向到详细信息视图.

I'd like to redirect to a detail view after I successfully submitted a form and created the object.

我的view.py

class ObjectCreateView(CreateView):
    model = Object
    form_class = ObjectCreateForm
    template_name = 'frontend/base/object_create.html'

  def get(self, request, *args, **kwargs):
      form = ForecastConfigurationCreateForm()
      form.fields['status'] = ModelChoiceField(queryset=ObjectStatus.get_object_status_list(self))
      return render(request, self.template_name, {'form': form})

  def post(self, request, *args, **kwargs):
      form = self.form_class(request.POST)
      if form.is_valid():
          self.fcc_form = form.save(commit=True)
          messages.add_message(self.request, messages.INFO, 'Good job!')
          return render_to_response(reverse(viewname='object_detail', kwargs={'uuid': self.fcc_form.uuid}))
      else:
          messages.add_message(self.request, messages.ERROR, 'Error!')
          return render(request, self.template_name, {'form': form})

错误消息是:

TemplateDoesNotExist位于/​​ object_create//object_detail/3a3d6279-1531-45d4-9ba9-b691886facf4/

TemplateDoesNotExist at /object_create//object_detail/3a3d6279-1531-45d4-9ba9-b691886facf4/

正在调用的URL是:

http://test.com:8000/object_create/?next =/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/

我想要的是

http://test.com:8000/object_detail/a5b2a693-6f90-4b98-b9a2-fc2fe6a90995/

谢谢!

推荐答案

而不是尝试呈现页面,而是使用 HttpResponseRedirect :

Instead of trying to render the page, use HttpResponseRedirect instead:

class ObjectCreateView(CreateView):
    ...

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            self.fcc_form = form.save(commit=True)
            messages.add_message(self.request, messages.INFO, 'Good job!')
            return HttpResponseRedirect(reverse('object_detail', kwargs={'uuid': self.fcc_form.uuid}))
        else:
            messages.add_message(self.request, messages.ERROR, 'Error!')
            return render(request, self.template_name, {'form': form})

这篇关于Django:创建后重定向到详细信息视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 08:06