【问题标题】:'QuerySet' object has no attribute 'META' 500(internal server erro)'QuerySet' 对象没有属性 'META' 500(内部服务器错误)
【发布时间】:2021-12-03 12:02:19
【问题描述】:

我正在尝试在 django 中练习 ajax,但出现此错误“QuerySet”对象没有属性“META”。但是由于错误,它在回溯中显示数据而不在模板中显示数据。如何解决这个问题?

models.py

from django.db import models

# Create your models here.


class Profile(models.Model):
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    bio = models.CharField(max_length=100)

    def __str__(self):
        return self.name

我认为这与视图有关,但我无法弄清楚。 视图.py

from django.shortcuts import render
from .models import Profile
from django.http import JsonResponse

# Create your views here.


def list(request):
    return render(request, 'livedata/list.html')


def getProfiles(request):
    profiles = Profile.objects.all()
    # print(JsonResponse({"profiles": list(profiles.values())}))
    return JsonResponse({"profiles": list(profiles.values())})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.list, name='list'),
    path('getProfiles', views.getProfiles, name='getProfiles')
]

index.html

{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    {% comment %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endcomment %}
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script src="{% static 'js/main.js' %}" defer></script>

    <title>Hello, world!</title>
  </head>
  <body>

    {% block contents %}{% endblock contents %}
    {% block scripts %}{% endblock scripts %}

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    {% comment %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> {% endcomment %}
    {% comment %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> {% endcomment %}
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  </body>
</html>

list.html

{% extends 'livedata/index.html' %}

{% block contents %}

    <h1>List of live data</h1>
    
    <ul id="display">

    </ul>



{% endblock contents %}

{% block scripts %}

<script>

$(document).ready(function () {
    setInterval(function () {
        $.ajax({
            type: 'GET',
            url: "{% url 'getProfiles' %}",
            success: function (response) {
                // console.log(response);
                $("#display").empty();
                for (var key in response.profiles) {
                    var temp = "<li>" + response.profiles[key].name + "</li>";
                    $("#display").append(temp);
                }
            },
            error: function (response) {
                alert("Error occured");
            }
        });
    }, 1000);
});

</script>

{% endblock scripts %}

【问题讨论】:

    标签: python django ajax


    【解决方案1】:

    您不应该将视图命名为listlist 是您在其他视图中使用的内置函数。通过定义一个名为list 的视图,list(profiles.values()) 将调用以profile.values() 作为请求的视图。

    例如,将list 重命名为view_list,并将网址格式更新为直接指向view_list

    def view_list(request):
        return render(request, 'livedata/list.html')
    
    
    def getProfiles(request):
        profiles = Profile.objects.all()
        #      does not refer to the view &downarrow; but to the list builtin
        return JsonResponse({"profiles": list(profiles.values())})

    urls.py 因此看起来像:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.view_list, name='list'),
        path('getProfiles', views.getProfiles, name='getProfiles')
    ]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 2020-10-31
      相关资源
      最近更新 更多