在Django中,当我更新发布日期时,如何更新get_absolute_url中的链接?

时间:2019-06-09 20:28:49

标签: python django

我构建了一个Django博客应用程序,并更新了发布日期 我发现get_absolute_url函数的结果未更新 它总是会获得原始链接

models.py

#-- models.py --
#Create custom manager
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from slugify import slugify

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,self).get_queryset().filter(status='published')
    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, slugify(self.slug)])

class Post(models.Model):
    objects = models.Manager()
    published = PublishedManager()
    STATUS_CHOICES = (('draft','Draft'),('published','Published'),)
    title = models.CharField(max_length = 250)
    slug = models.SlugField(max_length=250, unique_for_date = 'publish',allow_unicode=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now,blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    class Meta:
        ordering = ('-publish',)
    def __str__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, slugify(self.slug)])

Views.py

#--views.py--
from django.shortcuts import render, get_object_or_404,get_list_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .models import Post



def post_list(request):
    object_list = Post.published.all()
    paginator = Paginator(object_list, 3)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request,'blog/post/list.html',{'page':page,'posts':posts})

# Create second views
def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post,slug=post,status='published',publish__year=year,publish__month=month,publish__day=day)
    return render(request,'blog/post/detail.html',{'post':post})

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'blog/post/list.html'

模板 list.html

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

{% block title %} My Blog {% endblock %}

{% block content %}
  <h1> My Blog </h1>
  {% for post in posts %}
    <h2>
    <a href="{{ post.get_absolute_url }}">
      {{ post.title }}
    </a>
    </h2>
    <p class="date">
      Published {{ post.publish }} by {{ post.author }}
     </p>
     {{ post.body|truncatewords:30|linebreaks }}
  {% endfor %}
  {% include "pagination.html" with page=page_obj %}
{% endblock %}

代码已生成如下结果 http://localhost:8000/blog/2019/6/7/mydjango-first-time/

我希望结果应该更新为 http://localhost:8000/blog/2019/6/8/mydjango-first-time/

图片#1 the publihed date is updated 图片#2 get_absolute_url is not updated 图片#3 Page not found 图片#4 Expected result

我的第一个想法 我删除了该项目(在Django admin区域),并插入了一条具有所有相同数据(日期除外)的新记录,但仍然是相同的错误(找不到页面)。 甚至我尝试删除 pycache 文件夹中的缓存也不起作用。

1 个答案:

答案 0 :(得分:0)

您的发布字段未从我看到的代码中更新。您如何编辑帖子?通过前端的表单?如果是这样,您的视图代码应在保存后更新发布字段。

您的发布功能应为:

class Post(models.Model):
    ....

    def publish(self):
        self.publish = timezone.now()
        self.save()

    # or override the save
    def save(self, *args, **kwargs):
        if self.status == 'published':
            self.publish = timezone.now()
        return super(Post, self).save(*args, **kwargs)

或者通过信号方法(我将不在这里演示)来实现,您就会明白。主要是更新publish字段。