我最近开始学习Django并且在教程中遇到了一个奇怪的问题..
出于某种原因,如果我使用shell查询特定的'poll',则was_published_recently方法返回'true'。
我还编写了测试来检查pub_date是否“在一天前和现在之间”,并返回'true'..(所有测试都通过了)
但是,当我在管理面板中列出该民意调查时,它会返回'false'(“最近发布?”列)
有人可以帮我弄清楚我的代码有什么问题吗?
提前致谢!
这是我的polls/models.py
:
import datetime
from django.utils import timezone
from django.db import models
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(hours=2) <= self.pub_date < now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
这是polls/tests.py
文件:
import datetime
from django.utils import timezone
from django.test import TestCase
from polls.models import Poll
class PollMethodTests(TestCase):
def test_was_published_recently_with_future_poll(self):
future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
self.assertEqual(future_poll.was_published_recently(), False)
def test_was_published_recently_with_old_poll(self):
old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
self.assertEqual(old_poll.was_published_recently(), False)
def test_was_published_recently_with_recent_poll(self):
recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
self.assertEqual(recent_poll.was_published_recently(), True)
polls/admin.py
文件
from django.contrib import admin
from polls.models import Choice, Poll
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
admin.site.register(Poll, PollAdmin)
和polls/views.py
:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
""" Devuelve las ultimas 5 encuestas """
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.html'
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay poll voting form
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "Please choose an option",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Siempre devolver un HttpResponseRedirect despues de trabajar con
# POSTs. Esto evita que la informacion se inserte dos veces si el
# usuario le da al BACK.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
答案 0 :(得分:0)
您是否正确设置了settings.py中的时区? 我认为测试使用的是系统时间。但Webinterface正在使用您设置的时区。