无法将博客文章链接到特定类别Django [英] Unable to link Blog Posts to Specific Category Django

查看:138
本文介绍了无法将博客文章链接到特定类别Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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

 类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默认= 0)
slug = models.SlugField()

def save(self,* args,** kwargs):
#取消注释,如果你不想要每次更改名称
#if self.id为无:
#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 )
posts = Post.objects.filter(published_date__lte = timezone.now())。order_by('published_date')
返回渲染(请求,'rango / post_list.html',{'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)
如果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()
返回渲染(请求,'rango /post_edit.html',{'form':form})

def post_edit(request,pk):
post = get_object_or_404(Post,pk = pk)
如果请求.method ==POST:
form = PostForm(request.POST,instance = post)
如果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})

提前感谢

解决方案

我意识到我不得不将我的帖子过滤到各自的类别。我也切换到使用基于类的视图。代码有点清洁。

  class PostListView(DetailView):
model =类别
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')

上下文['posts'] =帖子
返回上下文


I used Tango with Django to create a database containing categories, and I used the Django Girls tutorial to add a blog to the database. Both are working fine, but I have been having trouble linking each blog post to its respective category. Right now, all posts go to my post_list.html page.

If I were doing this from scratch, I would add a new view, add a new template, add a url mapping, and then add a link from the category page. I also am aware that I need to edit my blog post model to contain:

category - models.ForeignKey(Category)

I thought it would be as simple as adding this to my url.py:

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

However after a few rounds of trying things along these lines, I can't quite get anything to work. I run into error after error. I have tried going through other blog-related tutorials online, and looking at other stack-overflow posts related to things like this, but I am still stuck. I am a newbie to Django; I am pretty sure that's playing a roll in my lack of success too.

Below is the (unmodified) code I have so far. Can someone help me with this?

My 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

My 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'),

My 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})

Thanks in advance.

解决方案

I realized I had to have my posts filtered to their respective categories. I also switched over to using class based views. The code is a little cleaner.

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

这篇关于无法将博客文章链接到特定类别Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆