首页 > 解决方案 > 无法将关键字“pub_”解析为 views.py 中的字段

问题描述

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

我按照教程的指示做了完全一样的,在 polls/templates/polls/index.html 中创建模板文件:

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 %}

还有views.py:polls/views.py¶

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))

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

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  

我认为它抱怨这条线:

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

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

标签: pythondjango

解决方案


您的代码中是否有一种“错字”:

(我猜)你写道:

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

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

你想编码:

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

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


推荐阅读