我正在使用django建立博客。
我的文章模型包括一个显示发布日期的字段:

publish = models.DateTimeField(default = timezone.now)


和一个get_absolute_url函数:

def get_absolute_url(self):
    return reverse('article:post_detail',
                args = [self.publish.year,
                        self.publish.strftime('%m'),
                        self.publish.strftime('%d'),
                        self.slug])


这是我显示文章的视图:

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Article, slug = post,
                                  status = 'published',
                                  publish__year = year,
                                  publish__month = month,
                                  publish__day = day)
return render(request, 'post.html', {'post': post})


这是我在博客项目中的网址:

url(r'^article/', include('article.urls', namespace = 'article',app_name = 'article')),


以及项目中文章应用的网址:

url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',views.post_detail, name = 'post_detail'),


我的预期结果是:当url为article为/article/2016/04/18/first-article/时,它将显示在特定日期发布的文章以及第一篇文章,但显示为:


  没有文章与给定查询匹配。


当我使用python manage.py shell品尝它时,我发现问题似乎与发布字段中的月份和日期有关:

>>> Article.objects.get(pk=1).get_absolute_url()
u'/article/2016/04/18/first-article/'
>>> Article.objects.get(pk=1).publish.year
2016
>>> Article.objects.get(pk=1).publish.month
4
>>> Article.objects.get(pk=1).publish.day
18


但是当我搜索文章时:

>>> from django.shortcuts import get_object_or_404
>>> get_object_or_404(Article, publish__year='2016')
<Article: This is the first article>
>>> get_object_or_404(Article, publish__year='2016', slug='first-article', status='published')
<Article: This is the first article>
>>> get_object_or_404(Article, publish__year='2016', publish__month='04')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/media/psf/Home/Porject/env/my_blog_new/lib/python2.7/site-packages/django/shortcuts.py", line 157, in get_object_or_404
  raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
Http404: No Article matches the given query.
>>> get_object_or_404(Article, publish__year='2016', publish__day='18')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/media/psf/Home/Porject/env/my_blog_new/lib/python2.7/site-packages/django/shortcuts.py", line 157, in get_object_or_404
    raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
Http404: No Article matches the given query.


似乎与月份和日期相关的所有内容均无效,但我无法弄清楚原因。
我使用的是mysql,尽管我认为它与此问题无关,因为我的主页工作正常。
是mysql处理datetime字段的bug?
我在这个问题上坚持了几天,并感谢任何意见和提示。先感谢您。

最佳答案

请在settings.py中将USE_TZ的值修改为False,

USE_TZ = False


Here是原始答案。

关于python - 无法通过Django中定义的网址获取对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36692253/

10-11 01:52