You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HttpResponse将correspondents变量输出到Django模板?

解决方法

首先明确两种常见需求场景,对应不同实现方式:

场景1:返回包含correspondents的JSON响应(适配AJAX调用)

现有视图仅返回状态信息,需将correspondents序列化后加入响应内容,同时修正原代码中获取联系人ID的语法错误:

修改后的views.py代码:

import json
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from .models import chatMessages

def send_chat(request):
    resp = {}
    User = get_user_model()
    if request.method == 'POST':
        post = request.POST
        try:
            u_from = User.objects.get(id=post['user_from'])
            u_to = User.objects.get(id=post['user_to'])
            # 保存聊天消息
            chatMessages.objects.create(user_from=u_from, user_to=u_to, message=post['message'])
            
            # 获取当前用户的所有联系人
            messages = request.user.received.all()
            # 提取所有消息发送者的ID(修正原代码的语法错误)
            sender_ids = messages.values_list('user_from__pk', flat=True).distinct()
            correspondents = User.objects.filter(pk__in=sender_ids)
            
            # 将用户对象序列化为可JSON解析的字典列表
            resp['correspondents'] = [
                {'id': user.id, 'username': user.username}  # 根据你的User模型字段调整字段名
                for user in correspondents
            ]
            resp['status'] = 'success'
        except Exception as ex:
            resp['status'] = 'failed'
            resp['mesg'] = str(ex)
    else:
        resp['status'] = 'failed'
        resp['mesg'] = '仅支持POST请求'

    return HttpResponse(json.dumps(resp), content_type="application/json")

场景2:渲染模板并传递correspondents变量(适配普通页面请求)

若需提交表单后直接渲染页面并在模板中使用correspondents,改用render函数返回模板响应:

修改后的views.py代码:

from django.shortcuts import render
from django.contrib.auth import get_user_model
from .models import chatMessages

def send_chat(request):
    User = get_user_model()
    resp = {}
    correspondents = User.objects.none()  # 初始化空查询集
    if request.method == 'POST':
        post = request.POST
        try:
            u_from = User.objects.get(id=post['user_from'])
            u_to = User.objects.get(id=post['user_to'])
            chatMessages.objects.create(user_from=u_from, user_to=u_to, message=post['message'])
            
            # 获取当前用户的所有联系人
            messages = request.user.received.all()
            sender_ids = messages.values_list('user_from__pk', flat=True).distinct()
            correspondents = User.objects.filter(pk__in=sender_ids)
            
            resp['status'] = 'success'
        except Exception as ex:
            resp['status'] = 'failed'
            resp['mesg'] = str(ex)
    else:
        resp['status'] = 'failed'
        resp['mesg'] = '仅支持POST请求'

    # 渲染模板并传递变量
    return render(request, 'chat_result.html', {
        'correspondents': correspondents,
        'response': resp
    })

对应模板chat_result.html的使用示例:

{% if response.status == 'success' %}
    <h3>消息发送成功</h3>
    <h4>你的联系人:</h4>
    <ul>
        {% for user in correspondents %}
            <li>{{ user.username }}</li>  <!-- 根据你的User模型字段调整显示内容 -->
        {% empty %}
            <li>暂无联系人</li>
        {% endfor %}
    </ul>
{% else %}
    <p>错误:{{ response.mesg }}</p>
{% endif %}

关键修正点

  • 原代码中UserModel需替换为get_user_model()返回的User模型,避免引用错误
  • 获取联系人ID时,需用values_list('user_from__pk', flat=True)替代错误的values(u_from.pk)写法
  • 序列化User对象时,必须提取具体字段(如id、username),不能直接序列化整个模型对象

内容的提问来源于stack exchange,提问作者Xrystik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:54:25