【问题标题】:Unable to link Blog Posts to Specific Category Django无法将博客文章链接到特定类别 Django
【发布时间】:2016-04-19 02:30:19
【问题描述】:

我使用 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 的新手;我很确定这也是我缺乏成功的原因。

下面是我到目前为止的(未修改的)代码。有人可以帮我弄这个吗?

我的模型.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'),

我的意见.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})

提前致谢。

【问题讨论】:

  • 你的问题是什么?到目前为止,您尝试过什么?
  • 同上@GwynBleidD 所说的。你描述了你的整个情况,你说你有很多错误,所以让我们从一个特定的错误开始。
  • 第一个错误-尝试进行迁移:您正在尝试添加一个不可为空的字段“类别”以在没有默认值的情况下发布;我们不能这样做(数据库需要一些东西来填充现有的行)。请选择修复 1) 现在提供一次性默认值(将在所有现有行上设置) 2) 退出,让我在 models.py 中添加默认值 我添加了 category = models.ForeignKey(Category) 来发布模型,并将 post_edit 的视图更新为以 def post_edit(request, pk, category_name_slug) 和 url(r'^category/(?P[\w\-]+)/post_edit/$', views.add_page, name='post_edit')
  • 好的,这是一个好的开始。对于可为空的字段,您需要:category = models.ForeignKey(Category, null=True)。还有什么?
  • 除了迁移它之外不需要做任何其他事情。模型必须导入 post_new views.py。我将其编辑为: def post_new(request, category_name_slug): 对于 url,post_new 应该类似于: url(r'^category/(?P[\w\-]+)/post_new/$' ,views.post_new,name='post_new'),这给了我这个错误:NoReverseMatch at /rango/category/rango/ Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found。尝试了 1 种模式:['rango/category/(?P[\\w\\-]+)/post_new/$'] 我不确定这是什么意思

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


【解决方案1】:

我意识到我必须将我的帖子过滤到各自的类别。我也切换到使用基于类的视图。代码更简洁一些。

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

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多