Skip to main content
 首页 » 编程设计

python之无法通过django中定义的url获取对象

2025年04月02日44txw1958

我正在使用 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]) 

这是我显示文章的 View :

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

以及项目内文章app的url:

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/ 时,它将首先显示在特定日期发布的文章,并带有 slug -文章,而是显示:

No article matches the given query.

当我使用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是原始答案。