django如何在泛型类中添加额外的参数

时间:2017-06-07 01:42:22

标签: django

前段时间我在每篇文章中都制作了一个带评论功能的简单博客应用。一切正常。这是我的模型,网址,视图和模板:

# model:
class Article(models.Model):
......
def get_absolute_url(self):
    return reverse('blog:article_detail', kwargs={'slug': self.slug})

# app/urls:
url(r'^article/(?P<slug>[-\w]+)/$', views.ArticleDetail.as_view(),name='article_detail'), 
url(r'^article/(?P<slug>[-\w]+)/comment/$',views.BlogCommentCreate.as_view(), name='blog_comment'),         

# views:        
class BlogCommentCreate(LoginRequiredMixin, CreateView):    
......
def get_context_data(self, **kwargs):  
    context = super(BlogCommentCreate, self).get_context_data(**kwargs)
    context['article'] = get_object_or_404(Article, slug=self.kwargs['slug'])
    return context

def form_valid(self, form):
    form.instance.user = self.request.user
    form.instance.article = get_object_or_404(Article, slug=self.kwargs['slug'])      
    return super(BlogCommentCreate, self).form_valid(form)        

# template        
<a href="{% url 'blog:blog_comment' article.slug %}">Add a new comment</a></p> 

但是当我将它们修改为此时,因为我想要一篇完整的文章网址:

# models:
def get_absolute_url(self):

return reverse('blog:article_detail',
    kwargs={
       'year': self.date_created.strftime('%Y'),
       'month': self.date_created.strftime('%m'),
       'day': self.date_created.strftime('%d'),
       'slug': self.slug})

# urls:           
url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',views.ArticleDetail.as_view(), name='article_detail'),
url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/comment/$',views.BlogCommentCreate.as_view(), name='blog_comment'),

出现错误:

NoReverseMatch at /blog/article/generating-dummy-post/comment/
Reverse for 'article_detail' with arguments '('generating-dummy-post',)' not found. 
1 pattern(s) tried: ['blog/article/(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/(?P[-\\w]+)/$']

如何在文章上下文中将这些(年,月,日)额外参数添加到我的视图和模板中?

0 个答案:

没有答案