2016-07-31 28 views
0

我正在關注一個教程來創建博客。 根據教程,代碼是正確的。 唯一的區別是,我使用Django 1.9,而不是1.8Django1.9:沒有模型匹配給定的查詢

調用視圖的Post模型,而不會

publish__year=year, 
publish__month=month, 
publish__day=day) 

沒有返回404錯誤 - No Post matches the given query.

這是view.py

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

該模型部分看起來像models.py

class Post(models.Model): 
    ... 
    publish = models.DateTimeField(default = timezone.now) 
    ... 

任何想法爲什麼查詢沒有找到?

編輯:

的URL看起來像localhost/blog/2016/07/30/second-post-entry/

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

看來,這些都是問題:

self.publish.strftime('%m'), # eg. == 07, but publish__month == 7 
self.publish.strftime('%d') # eg. == 30, publish__day == 30 
+0

如果您獲得'沒有帖子匹配給定的查詢',那意味着沒有匹配那年,每月和每天的帖子。我們不知道您在數據庫中發佈了什麼帖子,發佈日期是什麼,或者您嘗試訪問哪個網址,因此我們無法告訴您問題超出了這個範圍。 – Alasdair

+0

@Alasdair URL的結構是我在我的數據庫中找到的:'print(posts [1] .publish) 2016-07-30 17:47:28 + 00:00' – user2853437

+0

好的。 7!='07'self.publish.strftime('%m')!= publish__month ...那麼如何用0調用月份?現在什麼是正確的方式? – user2853437

回答

0

當我得到它,你可以更改self.publish.strftime('%m')self.publish.strftime('%d')self.publish.monthself.publish.day, 要麼你可以轉換將數據傳入int publish__year=int(year), publish__month=int(month), publish__day=int(day)。這應該夠了吧。

+0

@Alasdair @ Artem-Kolontay將'month ='07''轉換爲'int(月)'沒有幫助...所以我想知道。 我發現問題是在'setting.py'中輸入pytz'。 這樣就解決了這個問題。但不明白100%爲什麼。所以它與我的數據庫時間類型有關?有人可以解釋或轉介嗎? – user2853437

相關問題