我正在做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 import admin
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做同样的教程,并没有遇到同样的问题。我不确定这个问题是不是一个bug。
请告诉我如何解决此问题。感谢。
答案 0 :(得分:3)
试试这个:
pub_date = models.DateTimeField('date published')
在教程中,pub_date被定义为DateTimeField,使用它来比较日期时间值。
答案 1 :(得分:1)
使用它:
def was_published_recently(self):
now = timezone.now().date()
return now - datetime.timedelta(days=1) <= self.pub_date <= now