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

时间:2016-06-25 03:16:57

标签: django python-3.x django-models django-apps

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

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

2 个答案:

答案 0 :(得分:11)

我会去

var populations = populations.filter(function(d){
    return d.name != "";
});

当你有这样的帖子时:

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() 获取该类别下的帖子。

我已经编辑了你的代码,以显示我是如何编写的,如果这是我正在处理的项目。这是:

models.py

category.post_set.all()

views.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="Created at")
    updated_at = models.DateTimeField(auto_now=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

urls.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, '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})

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

答案 1 :(得分:2)

实际上这个方法(发布)只需要Django Girls教程,在shell https://tutorial.djangogirls.org/en/django_orm/中播放

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

由于行动由django admin管理,我会改变

published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at")

published_at = models.DateTimeField(null=True, blank=True, editable=True, default=timezone.now, verbose_name="Published at")

因此,在添加新帖子时,它会设置默认时间,您可以将其更改为适合您的任何内容。