【问题标题】:Have a blog with a max of 5 items [closed]拥有一个最多包含 5 个项目的博客 [关闭]
【发布时间】:2019-09-06 14:41:19
【问题描述】:

我目前有这个博客,但我想在某种程度上限制它:

models.py

class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
    )
    body = models.TextField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', args=[str(self.id)])

views.py

class BlogListView(ListView):
    model = Post
    template_name = 'home.html'


class BlogDetailView(DetailView):
    model = Post
    template_name = 'post_detail.html'


class BlogCreateView(CreateView):
    model = Post
    template_name = 'post_new.html'
    fields = ['title', 'author', 'body']


class BlogUpdateView(UpdateView):
    model = Post
    template_name = 'post_edit.html'
    fields = ['title', 'body']


class BlogDeleteView(DeleteView):
    model = Post
    template_name = 'post_delete.html'
    success_url = reverse_lazy('home')

urls.py

from .views import (
    BlogListView,
    BlogDetailView,
    BlogCreateView,
    BlogUpdateView,
    BlogDeleteView,
)

urlpatterns = [
    path('post/<int:pk>/delete/',
         BlogDeleteView.as_view(), name='post_delete'),
    path('post/<int:pk>/edit',
         BlogUpdateView.as_view(), name='post_edit'),
    path('post/new/', BlogCreateView.as_view(), name='post_new'),
    path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
    path('', BlogListView.as_view(), name='home'),
]

是否可以创建一个最多只允许 5 个项目的 Django blod,并且在第 5 个项目之后添加的任何内容都应该覆盖最旧的项目?如果有怎么做?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 这是一种不同的方法:列出博客帖子时,不要显示超过五个最近的帖子。当用户尝试访问帖子 (DetailView) 时,只需确保它是最近的五个帖子之一,否则返回 404 Not Found410 Gone 会更合适)。

标签: python django python-3.x


【解决方案1】:

您已经回答了自己的问题。发布新博文时,只需找到最近的五篇博文(包括刚刚发布的博文)并删除(或标记为隐藏)所有其他博文。

我发现简单地不允许访问较旧的博客帖子并仅检索五个最近的帖子会更有意义。这样您就可以将所有旧博客文章作为存档留给员工,并防止意外删除。

【讨论】:

  • 这就是我最终所做的。我将以下内容添加到模型blog = Blog.objects.order_by('-date')[:5]
  • 很有道理!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
相关资源
最近更新 更多