Django博客上的pk参数

jgwigjjp  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(132)

我在博客上工作,我按照指示,但现在我不明白为什么我有pk的问题。
这是我的views.py

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

def post_list(request):
    posts =  Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')
    latest_posts =  Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]

    context = {'posts': posts, 'latest_posts': latest_posts}
    return render(request, 'home.html', context)

def post_detail(request, post, pk):
    latest_posts =  Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
    post = get_object_or_404(Post, pk=pk)

    context = {'post': post, 'latest_posts': latest_posts}
    return render(request, 'post_detail.html', context)

这是blog/urls.py

urlpatterns = [
    path('', views.post_list, name='home'),
    path('<slug:post>/', views.post_detail,  name='post_detail'),
]

这是models.py

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")
    title = models.CharField(max_length=200, verbose_name="Title")
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE)
    body = RichTextField(blank=True, null=True)
    image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)})
    status = models.IntegerField(choices=STATUS, default=0)

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

    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

另外,我正在添加一个帖子列表,它可能与get_absolute_url有关

{% extends "base.html" %}
{% load static %} 
    {% block content %}
    <!-- Main Wrap Start -->
    <main class="position-relative">
        <div class="post-carausel-1-items mb-50">
            {% for post in latest_posts %}
            <div class="col">
                <div class="slider-single bg-white p-10 border-radius-15">
                    <div class="img-hover-scale border-radius-10">
                        <!--<span class="top-right-icon bg-dark"><i class="mdi mdi-flash-on"></i></span>-->
                        <a href="{{ post.get_absolute_url }}">
                            <img class="border-radius-10" src="{{ post.image.standard.url }}" alt="post-slider">
                        </a>
                    </div>
                    <h6 class="post-title pr-5 pl-5 mb-10 mt-15 text-limit-2-row">
                        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
                    </h6>
                    <div class="entry-meta meta-1 font-x-small color-grey float-left text-uppercase pl-5 pb-15">
                        <span class="post-by">By <a href="#">{{ post.author }}</a></span>
                        <span class="post-on">{{ post.created_at}}</span>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </main>
    {% endblock content%}

我有一个错误...

post_detail() missing 1 required positional argument: 'pk'

在我开始开发post detail之前,一切都很正常。你知道为什么会发生这种情况吗?

wooyq4lh

wooyq4lh1#

您似乎对模型的主键是什么感到困惑,主键是自动生成的idpk),但根据您的urls.py,您希望使用slug来获取记录。
首先,将您的路径更改为:

path('<slug:slug>/', views.post_detail, name='post_detail'),

然后将您的视图签名更改为:

def post_detail(request, slug):

最后,使用以下命令获取记录:

post = get_object_or_404(Post, slug=slug)

相关问题