函数'对象没有属性'对象

时间:2019-11-08 20:43:39

标签: python django

我正在尝试根据我的休闲教程遍历数据库,但是当我进入“列表”应用页面时,我得到Error: AttributeError at /listings/ - 'function' object has no attribute 'objects'

我已经尝试将变量命名为其他名称,这样它就不会与模型共享名称,但是不管我做什么。我仍然遇到错误

这就是清单应用中的views.py

from django.shortcuts import render
from listings.models import listing 
# Create your views here.


def index(request):
  listings = listing.objects.all()

  context = {
    'patients' : listings
  }
  return render(request, 'listings/listings.html')

def listing(request):
  return render(request, 'listings/listing.html')

那是我的urls.py

from django.urls import path 

from .import views

urlpatterns = [
  path('', views.index, name ='listings'),
  path('<int:listing_id>', views.listing, name ='listing'),

在这里,我要遍历数据并将其插入为给定格式

 {% if listings %}
        {% for listing in listings %}
        <div class="col-md-6 col-lg-4 mb-4">
          <div class="card listing-preview">
            <div class="card-body">
              <div class="listing-heading text-center">
                <h4 class="text-primary">Jane Doe</h4>
                <p>
                  <i class="fas fa-map-marker text-secondary"></i> Bishopstown Co,Cork</p>
              </div>
              <hr>
              <div class="row py-2 text-secondary">
                <div class="col-6">
                  <i class="fas fa-asterisk"> Risk:</i> Low</div>
              </div>
              <hr>
              <div class="row text-secondary pb-2">
                <div class="col-6">
                  <i class="fas fa-clock"></i> 2 days ago</div>
              </div>
              <hr>
              <a href="listing.html" class="btn btn-primary btn-block">More Info</a>
            </div>
          </div>
        </div>
        {% endfor %}
      {% else %}  
        <div class="col-md-12">
          <p>No Patients</p>
        </div>
      {% endif %}

我希望看到数据库中有一个条目,但我得到了Error: AttributeError at /listings/ - 'function' object has no attribute 'objects'request <WSGIRequest: GET '/listings/'>

1 个答案:

答案 0 :(得分:1)

您使用名称listing定义了一个函数,因为该函数是在导入后定义的,因此它将采用该函数。确实,我们看到了:

from listings.models import listing
# Create your views here.


def index(request):
  listings = listing.objects.all()

  context = {
    'patients' : listings
  }
  return render(request, 'listings/listings.html')

def listing(request):
  return render(request, 'listings/listing.html')

您可以通过本地导入来解决该问题:

# Create your views here.


def index(request):
  from listings.models import listing
  listings = listing.objects.all()

  context = {
    'patients' : listings
  }
  return render(request, 'listings/listings.html')

def listing(request):
  return render(request, 'listings/listing.html')

但是对于Django模型(以及一般类),建议使用 Perl Case 。因此,您可能应该将 listing 模型重命名为Listing