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

Django新手求助:Ajax实现数据库上传及通知功能异常排查

问题分析与修正方案

我帮你梳理一下代码里的几个关键问题,这些问题直接导致了Ajax请求无法正常完成数据上传:

1. 事件绑定逻辑错误

你的Ajax代码绑定了#request-btn的submit事件,但这个元素是按钮而非表单,表单才是触发submit事件的主体。应该绑定表单#notify_form的submit事件,或者按钮的click事件。

2. 数据库字段赋值错误

在views.py中,你把notification定义成了一个元组:

notification = user, "have intrested in your property", property_object.headline

而Model里的notification是TextField类型,需要传入字符串而非元组,否则会存储成类似(<User: xxx>, 'have intrested...', '房源标题')的异常格式。

3. Ajax回调的语法错误

成功回调里的判断语句if(data,msg == "success")存在语法错误,正确的写法应该是if(data.msg === "success"),这里的逗号是误用,需要用点号访问JSON对象的属性。

4. Model方法名拼写错误

models.py里的__str_少了一个下划线,正确的魔法方法名应该是__str__,否则在后台管理页面或打印对象时会显示异常。

5. Owner查询的潜在风险

你的表单里owner_id的value是{{ accomodation.owner }},这会输出User对象的__str__返回值(通常是用户名),如果用户名重复或者__str__的定义不是用户名,会导致User.objects.get(username=owner)查询报错。更稳妥的方式是传递用户ID,通过ID查询用户。


修正后的完整代码

models.py

class Notifications(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE)
    property = models.ForeignKey(Property, null=True, blank=True,on_delete=models.CASCADE)
    notification = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):  # 修正方法名拼写
        return self.notification

views.py

from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

@login_required  # 新增:确保只有登录用户能发送通知
def notification(request):
    user = request.user
    if request.method == 'POST':
        try:
            # 用get方法获取参数,避免KeyError
            property_id = request.POST.get('property_id')
            owner_id = request.POST.get('owner_id')
            
            property_object = Property.objects.get(id=property_id)
            owner_object = User.objects.get(id=owner_id)  # 通过ID查询用户,更可靠
            
            # 拼接成符合要求的字符串
            notification_content = f"{user.username} has shown interest in your property: {property_object.headline}"
            
            property_object.notify.add(user)
            # create方法会自动保存,无需额外调用save()
            Notifications.objects.create(
                notification=notification_content, 
                property=property_object, 
                owner=owner_object
            )
            return JsonResponse({'msg':'success'})
        except (Property.DoesNotExist, User.DoesNotExist):
            # 处理对象不存在的异常,返回错误信息
            return JsonResponse({'msg':'error', 'detail':'Property or user not found'}, status=400)
    else:
        return JsonResponse({'msg':'error', 'detail':'Invalid request method'}, status=405)

前端表单与Ajax代码

<form action="{% url 'notification' %}" method="post" id="notify_form" >
    {% csrf_token %}
    <!-- 改为传递owner的ID,而非对象本身 -->
    <input type="hidden" name="owner_id" value="{{ accomodation.owner.id }}">
    <button id="request-btn" name="property_id" value="{{ accomodation.id }}" class="btn btn-primary">Contact info:</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        // 绑定表单的submit事件
        $('#notify_form').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                url:"{% url 'notification' %}",
                data:$(this).serialize(),  // 用this指代当前表单,代码更简洁
                dataType:'json',  // 改为小写的json,jQuery对大小写敏感
                success:function(data){
                    if(data.msg === "success"){
                        alert('Notification sent successfully!');
                    } else {
                        alert('Error: ' + data.detail);
                    }
                },
                error:function(xhr, status, error){
                    // 新增错误处理,方便调试
                    alert('Request failed: ' + error);
                }
            });
        });
    });
</script>

额外建议

  • 确保在urls.py中正确配置了视图路由:path('notification/', views.notification, name='notification')
  • 保留异常处理逻辑,避免因非法参数导致服务器崩溃
  • dataType参数必须是小写的'json',否则jQuery可能无法正确解析响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:52:43