首页 > 解决方案 > Django收到POST请求后如何更新页面?

问题描述

我是 Django 的新手。

每次应用程序收到 POST 请求时,我想更新浏览器中的页面。目前,我使用 POSTMAN 发送 POST 请求。最后,它是另一个网络服务器,它将通过 POST 请求发送数据。

我没有找到任何解决方案来做到这一点。

这是我认为的代码:

@csrf_exempt
def prem(request):

    if request.method == 'GET':
        print("GET")
        context = {'contenu': request.GET.get("request_received", "nothing") }
    elif request.method == 'POST':
        print("POST")
        datar = request.GET.get('request_received','rien')
        context = { 'request_received' : datar }

    return render(request, 'polls/seco.html', context)

我的模板中的代码:

{% if request_received %}
    {% csrf_token %}
    <p>Message received from POST request : {{ request_received }}</p>
{% endif %}

有人可以帮助我吗?

标签: djangodjango-templatesdjango-views

解决方案


From what you have written (in the comments ), it seems you want the webpage to dynamically update in real time (without reloading) whenever a request is received.

This is technicaly not possible as django does not maintain connection with client once the response has been sent.

You will have to save the incoming post request(from POSTMAN) to db.

Then in the templete , you can either use AJAX to continuously check whether a new request has arrived or make use of websockets to retain connection with user.

Websockets are faster than AJAX. Thus they are what you want as you wrote 'instantly' in comments. AJAX request can take a few seconds in the worst case.

In django , you can use django-channels for websockets

django channels


推荐阅读