无法将关键字“ pub_”解析为views.py中的字段

时间:2019-03-03 09:27:38

标签: python django

在以下教程中, https://docs.djangoproject.com/en/2.1/intro/tutorial03/

我所做的操作与本教程完全相同,请在polls / templates / polls / index.html中创建模板文件:

Object

和views.py: polls /views.py¶

polls/templates/polls/index.html¶
{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

启动服务器并访问URL:http://127.0.0.1:8000/polls/时,出现以下错误:

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

我认为它抱怨这一行:

FieldError at /polls/
Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/
Django Version: 2.1.7
Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text
Exception Location: /home/martin/anaconda3/envs/web/lib/python3.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1389
Python Executable:  /home/martin/anaconda3/envs/web/bin/python
Python Version: 3.7.2
Python Path:    
['/home/martin/nlp/web/web',
 '/home/martin/anaconda3/envs/web/lib/python37.zip',
 '/home/martin/anaconda3/envs/web/lib/python3.7',
 '/home/martin/anaconda3/envs/web/lib/python3.7/lib-dynload',
 '/home/martin/anaconda3/envs/web/lib/python3.7/site-packages']
Server time:    Sun, 3 Mar 2019 09:20:08 +0000
Error during template rendering
In template /home/martin/nlp/web/web/polls/templates/polls/index.html, error at line 1

Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text
1   {% if latest_question_list %}
2       <ul>
3       {% for question in latest_question_list %}
4           <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
5       {% endfor %}
6       </ul>
7   {% else %}
8       <p>No polls are available.</p>
9   {% endif %}
10  

我在应用程序的终端上运行此行,但没有发现问题。但是当我在服务器上运行该应用程序时,总是遇到这个烦人的问题。

1 个答案:

答案 0 :(得分:1)

您的代码中是否有“错别字”。

(我想)您写过:

  

Question.objects.order_by('-pub_date'[:5])

这意味着“所有问题都以名为'pub_'的字段降序排列” ,因为'-pub_date'[:5]'-pub_'

您要编码:

  

Question.objects.order_by('-pub_date')[:5]

这意味着“最近的五个问题”