无法将博客帖子链接到特定类别Django

时间:2016-01-13 22:18:42

标签: python django django-models django-views django-urls

我使用Tango和Django创建一个包含类别的数据库,我使用Django Girls教程将博客添加到数据库中。两者都运行良好,但我一直无法将每个博客帖子链接到各自的类别。现在,所有帖子都会转到我的post_list.html页面。

如果我从头开始这样做,我会添加一个新视图,添加一个新模板,添加一个url映射,然后从类别页面添加一个链接。我也知道我需要编辑我的博客文章模型以包含:

category - models.ForeignKey(Category)

我认为这就像将其添加到我的url.py中一样简单:

url(r'^category/(?P<category_name_slug>[\w\-]+)/post_edit/$', views.add_page, name='add_page'),  

然而,经过几轮尝试这些方面的事情后,我无法完成任何工作。错误后我遇到错误。我已经尝试在线浏览其他与博客相关的教程,并查看与此类相关的其他堆栈溢出帖子,但我仍然卡住了。我是Django的新手;我很确定这也是因为我缺乏成功。

以下是我迄今为止的(未经修改的)代码。有人可以帮我弄这个吗?

我的models.py

class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
        default=timezone.now)
published_date = models.DateTimeField(
        blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
            # Uncomment if you don't want the slug to change every time the name changes
            #if self.id is None:
                    #self.slug = slugify(self.name)
            self.slug = slugify(self.name)
            super(Category, self).save(*args, **kwargs)

    def __unicode__(self):  #For Python 2, use __str__ on Python 3
        return self.name

我的urls.py

    url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
    url(r'^post_list/$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),

我的views.py

 def post_list(request):
 posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
 return render(request, 'rango/post_list.html', {'posts': posts})

def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'rango/post_detail.html', {'post': post})

def post_new(request):
if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.published_date = timezone.now()
        post.save()
        return redirect('post_detail', pk=post.pk)
else:
    form = PostForm()
return render(request, 'rango/post_edit.html', {'form': form})

def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
    form = PostForm(request.POST, instance=post)
    if form.is_valid():
        post = form.save(commit=False)
        post.author = request.user
        post.published_date = timezone.now()
        post.save()
        return redirect('post_detail', pk=post.pk)
else:
    form = PostForm(instance=post)
return render(request, 'rango/post_edit.html', {'form': form})

提前致谢。

1 个答案:

答案 0 :(得分:0)

我意识到我必须将我的帖子过滤到各自的类别。我还切换到使用基于类的视图。代码有点干净。

class PostListView(DetailView):
model = Category
template_name = 'dicer/post_list.html'

def get_context_data(self, **kwargs):
    context = super(PostListView, self).get_context_data(**kwargs)
    posts = (
        Post.objects.filter(category=self.get_object(),
                            published_date__lte=timezone.now())
                    .order_by('published_date')
    )
    context['posts'] = posts
    return context