【发布时间】:2017-04-23 19:44:06
【问题描述】:
我正在学习 Django 1.8 教程来制作投票应用程序:
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
我添加了一个名为 was_published recent() 的布尔函数,如果最近发布了一篇文章,它将返回 True 或 False。 该函数在这里定义在 Question 类下
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
return self.question_text
此外,我设置了一个管理员来显示问题,如下所示: 从 django.contrib 导入管理员
from .models import Choice,Question
class ChoiceInLine(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['question_text']}),
('Date information', {'fields':['pub_date'],'classes':['collapse']}),
]
inlines = [ChoiceInLine]
list_display = ('question_text','pub_date','was_published_recently')
admin.site.register(Question, QuestionAdmin)
但是,当我访问管理员的问题部分时,我收到一条错误消息:
TypeError at /admin/polls/question/
can't compare datetime.datetime to datetime.date
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/polls/question/
Django Version: 1.8.3
Exception Type: TypeError
Exception Value:
can't compare datetime.datetime to datetime.date
Exception Location: C:\Users\Owner\Desktop\venv\forumtest\polls\models.py in was_published_recently, line 12
Python Executable: C:\Users\Owner\Desktop\venv\Scripts\python.EXE
Python Version: 3.4.2
Python Path:
['C:\\Users\\Owner\\Desktop\\venv\\forumtest',
'C:\\Windows\\system32\\python34.zip',
'C:\\Users\\Owner\\Desktop\\venv\\DLLs',
'C:\\Users\\Owner\\Desktop\\venv\\lib',
'C:\\Users\\Owner\\Desktop\\venv\\Scripts',
'C:\\Python34\\Lib',
'C:\\Python34\\DLLs',
'C:\\Users\\Owner\\Desktop\\venv',
'C:\\Users\\Owner\\Desktop\\venv\\lib\\site-packages']
Server time: Wed, 22 Jul 2015 16:30:07 -0700
Error during template rendering
In template C:\Users\Owner\Desktop\venv\lib\site-packages\django\contrib\admin\templates\admin\change_list.html, error at line 91
can't compare datetime.datetime to datetime.date
81 {% endif %}
82 {% endblock %}
83
84 <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %} novalidate>{% csrf_token %}
85 {% if cl.formset %}
86 <div>{{ cl.formset.management_form }}</div>
87 {% endif %}
88
89 {% block result_list %}
90 {% if action_form and actions_on_top and cl.show_admin_actions %}{% admin_actions %}{% endif %}
91
{% result_list cl %}
92 {% if action_form and actions_on_bottom and cl.show_admin_actions %}{% admin_actions %}{% endif %}
93 {% endblock %}
94 {% block pagination %}{% pagination cl %}{% endblock %}
95 </form>
96 </div>
97 </div>
98 {% endblock %}
99
我使用的是 django 1.8,我用 1.7 做了同样的教程,没有遇到同样的问题。我不确定这个问题是否是一个错误。
请告诉我如何解决此问题。谢谢。
【问题讨论】: