
[英]Django form redirect after POST is unreliable and needed a success_url
[英]how I can prevent CreateView ( django 1.6) redirect me to the success_url if the form is valid and so just return a json?
我尝试覆盖返回json而不是HttpResponseRedirect的form_valid方法,但这不起作用。 请向我提出以下错误: "The view did not return an HttpResponse object."
这是我认为的代码:
from django.views.generic import CreateView
from django.shortcuts import render
from django.http import HttpResponse
from .forms import TestForm
import json,urllib2
class CreateViewTest(CreateView):
form_class=TestForm
template_name="Test.html"
success_url = ""
def form_valid(self, form):
urllib2.urlopen('returnjson/',json.dumps(form.data))
#returning here try different things but all gave me the same error
试试这个吧。
import json
class CreateViewTest(CreateView):
form_class = TestForm
template_name = 'test.html'
def form_valid(self, form):
# return an HttpResponse object
return HttpResponse(json.dumps(form.data), content_type="application/json")
import json
from django.http import HttpResponse
def form_valid(self, form):
return HttpResponse(json.dumps(form.data), content_type='application/json')
另外,出于可重用性的考虑,我建议您创建一个mixin
,仅在请求为AJAX时才负责呈现JSON响应:
from django.views.generic.edit import FormMixin
class JsonResponseFormMixin(FormMixin):
def form_valid(self, form):
if self.request.is_ajax():
return HttpResponse(json.dumps(form.data), content_type='application/json')
return super(JsonResponseFormMixin, self).form_valid(form)
def form_invalid(self, form):
if self.request.is_ajax():
return return HttpResponse(json.dumps(form.errors), content_type='application/json', status_code=400)
return super(JsonResponseFormMixin, self).form_valid(form)
from django.views.generic import CreateView
from .forms import TestForm
class CreateViewTest(CreateView, JsonResponseFormMixin):
form_class = TestForm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.