首先我使用一个详细列表与def工作正常,但我想添加一个小部件来显示类似的帖子(在同一类别中发布)所以我不得不将我的def更改为一个类来放置一个def get_context_data(self,pk ),但现在它总是说et_context_data()得到一个意外的关键字参数'对象'
这是我的网址
url(r'^(?P<slug>[\w-]+)$', views.postdetails.as_view(), name="postdetails"),
我的看法
class postdetails(DetailView):
model = Post
template_name = 'blog/post.html'
def get_context_data(self,**kwargs):
context = super(postdetail, self).get_context_data(**kwargs)
cat_id = self.kwargs.get('pk', None)
category = get_object_or_404(Category, id=cat_id)
getcat = category.post_set.all().order_by("-date")
resultcat = random.sample(getcat,4)
context['similarpost'] = resultcat
return context
和我的模型如果需要的话
class Post(models.Model):
title = models.CharField(max_length = 140, unique=True)
slug = models.SlugField(max_length=40, blank=True, unique=True)
image = models.ImageField(upload_to="media", blank=True)
body = RichTextField(config_name='default')
date = models.DateField()
category = models.ManyToManyField(Category)
def __str__(self):
return self.title
我在def get_context_data(self,pk)中更改了pk:到了** kwargs但我得到的名字'postdetail'没有定义
非常感谢