Django 表单验证失败后返回什么?

发布于 2024-11-10 12:39:13 字数 871 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘逸的'云 2024-11-17 12:39:13

会话对此很有用,或者如果您使用 AJAX,您可以验证表单,然后在失败后返回您的对象或某种错误消息或您想要的任何内容。其中之一可能是最好的。您还可以将 POST 请求中的参数作为 GET 查询参数传递到重定向视图,或将参数传递到重定向视图:

from django.shortcuts import redirect
return redirect('some-view-name', reviewID=id)

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:

from django.shortcuts import redirect
return redirect('some-view-name', reviewID=id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文