Django:创建后重定向到详细信息视图

时间:2018-10-01 20:31:10

标签: django django-views

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

我的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 /

正在调用的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/

谢谢!

2 个答案:

答案 0 :(得分:1)

使用HttpResponseRedirect代替尝试呈现页面:

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})

答案 1 :(得分:0)

偶然发现答案。返回值应该是:

return redirect(reverse('object_detail', kwargs={'uuid': self.fcc_form.uuid}))