加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在我的django博客中添加类别

发布时间:2020-12-20 12:10:52 所属栏目:Python 来源:网络整理
导读:我使用 djangogirls.com教程开发了一个django博客应用程序.我想添加一个博客类别,但我不能这样做! 我在疯狂地搜索谷歌和stackoverflow.com,但是,作为python / django的新手,我无法成功地将类别添加到我的博客中. 我的模特: from django.db import modelsfr
我使用 djangogirls.com教程开发了一个django博客应用程序.我想添加一个博客类别,但我不能这样做!

我在疯狂地搜索谷歌和stackoverflow.com,但是,作为python / django的新手,我无法成功地将类别添加到我的博客中.

我的模特:

from django.db import models
from django.utils import timezone 

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

我的观点:

from django.shortcuts import render,get_object_or_404
from django.utils import timezone
from .models import Post

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

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

我的网址:

from django.conf.urls import include,url
from . import views

urlpatterns = [
    url(r'^$',views.post_list,name='post_list'),url(r'^post/(?P<pk>d+)/$',views.post_detail,name='post_detail'),]

我的post_list.html:
?????{%extends’blog / base.html’%}

{% block content %}
   {% for post in posts %}
      <div class="post">
          <div class="date">
              {{ post.published_date }}
          </div>
              <h1><a href="{% url 'post_detail' pk=post.pk %}">{{post.title }}</a></h1>
        <p>{{ post.text|truncatewords:100}}</p>
    </div>
  {% endfor %}
{% endblock %}

我的post_detail.html:

{% extends 'blog/base.html' %}

{% block content %}
    <div class="post">
       {% if post.published_date %}
           <div class="date">
              {{ post.published_date }}
           </div>
      {% endif %}
      <h1>{{ post.title }}</h1>
    <p>{{ post.text|linebreaks }}</p>
 </div>
{% endblock %}

好.如果有人可以帮助我,我需要为这个博客模型创建一个类别模型,我真的很感激!
提前致谢!

解决方法

我会去的

class Category(models.Model):
    title = models.CharField(max_length=255,verbose_name="Title")
    ...


class Post(models.Model):
    category = models.ForeignKey(Category,verbose_name="Category")
    title = models.CharField(max_length=255,verbose_name="Title")
    text = models.TextField()
    ...

当你有这样的帖子时:

post = Post.objects.first()

您可以使用post.category.title访问它的类别标题,或者当您有类似这样的类别时:

category = Category.objects.first()

您可以使用category.post_set.all()获取该类别下的帖子.

我编辑了你的代码,以显示我是如何编写的,如果这是我正在进行的项目.这里是:

models.py

from django.db import models
from django.utils import timezone 

class Category(models.Model):
    created_at = models.DateTimeField(auto_now_add=True,verbose_name="Created at")
    updated_at = models.DateTimeField(auto_now=True,verbose_name="Updated at")
    title = models.CharField(max_length=255,verbose_name="Title")

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __str__(self):
        return self.title

class Post(models.Model):
    created_at = models.DateTimeField(auto_now_add=True,verbose_name="Updated at")
    is_published = models.BooleanField(default=False,verbose_name="Is published?")
    published_at = models.DateTimeField(null=True,blank=True,editable=False,verbose_name="Published at")
    category = models.ForeignKey(Category,verbose_name="Category")
    author = models.ForeignKey('auth.User',verbose_name="Author")
    title = models.CharField(max_length=200,verbose_name="Title")
    text = models.TextField(verbose_name="Text")

    class Meta:
        verbose_name = "Post"
        verbose_name_plural = "Posts"
        ordering = ['-created_at']

    def publish(self):
        self.is_published = True
        self.published_at = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render,get_object_or_404
from django.utils import timezone
from .models import Category,Post

def category_list(request):
    categories = Category.objects.all() # this will get all categories,you can do some filtering if you need (e.g. excluding categories without posts in it)

    return render (request,'blog/category_list.html',{'categories': categories}) # blog/category_list.html should be the template that categories are listed.

def category_detail(request,pk):
    category = get_object_or_404(Category,pk=pk)

    return render(request,'blog/category_detail.html',{'category': category}) # in this template,you will have access to category and posts under that category by (category.post_set).

def post_list(request):
    posts =  Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at')

    return render(request,{'post': post})

urls.py

from django.conf.urls import include,url
from . import views

urlpatterns = [
    url(r'^category$',views.category_list,name='category_list'),url(r'^category/(?P<pk>d+)/$',views.category_detail,name='category_detail'),url(r'^$',]

我没有写模板,他们取决于你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读