使用AJAX更新Django模板中的数据

时间:2020-07-02 20:14:28

标签: python django ajax django-templates

我建立了一个简单的消息传递系统。每当有新消息时,我都想更新收件箱div。

html:

<div id="inbox">
            <h6>Inbox</h6>
            {% for message in inbox %}
                <ul>
                    <li title="{{ message.sender.username }}">{{ message.sender.first_name }}: {{ message.msg_content }}
                        <button onclick="myFunction()">Reply</button>
                    </li>
                    <small>-{{ message.timestamp }}</small>
                    <hr>
                </ul>
            {% endfor %}
        </div>

观看次数:

def user_messages(request):
    time_now = datetime.datetime.now()
    user = request.user

    if request.method == "POST":
        sender = request.user
        receiver_name = request.POST.get('msg_receiver')
        receiver = User.objects.get(username=receiver_name)
        msg_content = request.POST.get('msg_content')

        Messages.objects.create(sender=sender, receiver=receiver, msg_content=msg_content)

    inbox = Messages.objects.filter(receiver=user).order_by('-timestamp')
    outbox = Messages.objects.filter(sender=user).order_by('-timestamp')

    context = {'inbox': inbox, 'outbox': outbox, 'time_now': time_now}

    return render(request, 'accounts/messages.html', context)

每当收件箱中有一封新邮件时,即收件箱的长度更大,我希望div(id = inbox)进行更新。

我在html文件中添加了一个脚本:

$('.inbox').click(function () {
            $.ajax(
                {
                    type: "GET",
                    url: "{% url 'messages' %}",
                    data: {
                        
                    },
                })
        });

如何检查对象模型中的更改?

0 个答案:

没有答案