Django 表单验证失败后返回什么?
django 表单验证失败后如何返回我的页面?
这就是我现在所拥有的,在我的表单对象和我需要传回的所有其他对象失败后,我返回一个 render_to_response 。但是浏览器中的 url 具有表单操作的值,所以这看起来对我来说就好像我做错了什么一样。我更希望能够以某种方式返回对象以及 HttpResponseRedirect,但查看文档是不可能的。
def addReview(request,reviewId):
review = AdminReview.objects.get(id=int(reviewId))
if request.method == 'POST':
form = UserReviewForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
ur = UserReview(adminReview=review,review=cd['review'],rating=int(cd['rating']))
ur.save()
return HttpResponseRedirect(reverse('filmflux.reviews.views.review', kwargs={'reviewId':review.id,'filmSlug':review.filmSlug}))
userReviews = review.userreview_set.all()
return render_to_response('review.html', {'review':review,'form': form, 'userReviews': userReviews }, context_instance=RequestContext(request))
How shall I return to my page after a django form has failed validation?
This is what I have at the moment, I return a render_to_response after it has failed with my form objects and all the other objects I need to pass back in. But The url in the browser has the value of the form action and so this seems to me as if I'm doing something wrong. I would prefer if I could somehow return the objects along with a HttpResponseRedirect but looking at the docs that is not possible.
def addReview(request,reviewId):
review = AdminReview.objects.get(id=int(reviewId))
if request.method == 'POST':
form = UserReviewForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
ur = UserReview(adminReview=review,review=cd['review'],rating=int(cd['rating']))
ur.save()
return HttpResponseRedirect(reverse('filmflux.reviews.views.review', kwargs={'reviewId':review.id,'filmSlug':review.filmSlug}))
userReviews = review.userreview_set.all()
return render_to_response('review.html', {'review':review,'form': form, 'userReviews': userReviews }, context_instance=RequestContext(request))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
会话对此很有用,或者如果您使用 AJAX,您可以验证表单,然后在失败后返回您的对象或某种错误消息或您想要的任何内容。其中之一可能是最好的。您还可以将 POST 请求中的参数作为 GET 查询参数传递到重定向视图,或将参数传递到重定向视图:
Sessions would be good for this, or if you use AJAX you can validate the form, then return your object or some sort of error message or whatever you want after a failure. One or the other would probably be best. You could also pass params from the POST request along as GET query params to the redirected view, or pass arguments to the redirected view: