在这种情况下使用slug并使其正常工作的最佳方法是什么?我可以看到浏览器上的 URL 显示请求的项目,但我无法呈现详细页面。我找不到问题来自哪里。当我访问"page_detail"时,url 是"http://127.0.0.1:8000/posts/2019/03/23/greetings/",根据我的输入,这是正确的,但 django 抛出错误来呈现页面。错误是:TypeError: post_detail() got an unexpected keyword argument 'slug'
型:
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
published = PublishedManager() # Custom Model Manager
def get_absolute_url(self):
''' Canonical URL for post detail.'''
return reverse('snippets:post-detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
网址
app_name = 'snippets'
urlpatterns = [
path('posts/', views.post_list, name='post-list'),
path('posts/<int:year>/<int:month>/<int:day>/<slug:slug>/', views.post_detail, name='post-detail'),
]
视图
def post_list(request):
posts = Post.published.all()
context = {'posts': posts}
return render(request, 'snippets/list.html', context)
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, 'snippets/detail.html', {'post':post})
post_list
网页{% extends "base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
post_detail
网页{% extends "base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
{% endblock %}
我仍然被困住了。任何帮助将不胜感激。
尝试将 views.py 更改为
def post_detail(request, year, month, day, slug):
post = get_object_or_404(Post, slug=slug,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'snippets/detail.html', {'post':post})