我按照Django by Example这本书写了一篇博客。
# blog/models.py
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='publish')
author = models.ForeignKey(
User, related_name='blog_posts', on_delete=models.CASCADE)
body = models.TextField()
publish = models.DateTimeField(default=timezone.localtime)
class Meta:
ordering = ('-publish', )
def __str__(self):
return self.title
url config:
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:year>/<int:month>/<int:day>/<str:slug>', views.post_detail, name='post_detail'),
]
当我收到blog/views.py
中的帖子时:
def post_detail(request, year, month, day, slug):
post = get_object_or_404(
Post,
slug=slug,
publish__year=year,
publish__month=month,
publish__day=day
)
return render(request, 'blog/post_detail.html', {'post': post})
它返回404.
Page not found (404)
Request Method: GET
Request URL: http://localhost/blog/2017/12/9/its-code-now
Raised by: blog.views.post_detail
No Post matches the given query.
如果我修改blog/views.py
,只过滤年份,则返回正常:
def post_detail(request, year, month, day, slug):
post = get_object_or_404(
Post,
slug=slug,
publish__year=year,
)
return render(request, 'blog/post_detail.html', {'post': post})
问题似乎是publish__month
。但是Django支持这种方法。
我无法弄清楚如何解决它。