![](/img/trans.png)
[英]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.