简体   繁体   English

Django处理POST数据后返回成功/失败

[英]Django return successful/failure after processing POST data

How do I let client side know that Django has processed POST data successfully or not? 如何让客户端知道Django已成功处理POST数据? If yes, it will reset the current views, if not it should raise a notification alert. 如果是,它将重置当前视图,否则将引发通知警报。

def test_page(request):
    if request.method == "POST":
        newgroup = request.POST["group"]
        print "Received result"
        # assert validateGroup(newgroup)
        t = Trial(group = newgroup, time = timezone.now(), subject = request.user)
        t.save()

    return render_to_response('interface/test.html',\
                    context_instance=RequestContext(request))

This is what I did, but definitely there's no try and catch block. 这是我所做的,但是绝对没有任何尝试捕获块。

You can use the Django messages framework 您可以使用Django消息框架

Quite commonly in web applications, you need to display a one-time notification message (also known as “flash message”) to the user after processing a form or some other types of user input. 在Web应用程序中,通常很常见,您需要在处理表单或某些其他类型的用户输入后向用户显示一次性通知消息(也称为“即时消息”)。

https://docs.djangoproject.com/en/1.7/ref/contrib/messages/ https://docs.djangoproject.com/en/1.7/ref/contrib/messages/

Alternatively, you can add an extra variable to your template and display errors in the page. 另外,您可以在模板中添加一个额外的变量,并在页面中显示错误。

def test_page(request):
    if request.method == "POST":
        try:
            # form-processing code
        except ValueError:
            # go back to previous page and show errors
            return render(request, 'previous_page.html',
                {'errors'=['Problem!']})

    # this will be rendered when above exception is not encountered
    return render_to_response('interface/test.html',\
                    context_instance=RequestContext(request))

And in the template ( previous_page.html ), you can do this: 在模板( previous_page.html )中,您可以执行以下操作:

{% for err in errors %}
    <div class="error-box">
        { err }
    </div>
{% endfor %}

Where the error-box class highlights your error messages as dismiss-able notifications or however you want to show it. error-box类将您的错误消息突出显示为可取消的通知,或者您想显示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM