如何在Django 3中实现Post和Category模型的视图和url模式



我正试图通过构建一个简单的博客来学习Django。我有三种型号:Post、Category和Tag。

class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True, null=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
updated_on = models.DateTimeField(auto_now=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=POST_STATUS, default=0)
visibility = models.IntegerField(choices=POST_VISIBILITY, default=0)
content = models.TextField()
excerpt = models.TextField()
category = models.ForeignKey('blog.Category', on_delete=models.CASCADE)
tags = models.ManyToManyField('blog.Tag')
image = models.ImageField(upload_to="images/", default=0)
class Meta:
ordering = ['-created_on', 'title']
verbose_name = 'Post'
verbose_name_plural = 'Posts'
unique_together = ('title', 'slug')
def __str__(self):
return self.title

class Category(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True, null=False)
description = models.TextField()
class Meta:
ordering = ['title']
verbose_name = 'Category'
verbose_name_plural = 'Categories'
unique_together = ('title', 'slug')
def __str__(self):
return self.title

class Tag(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True, null=False)
description = models.TextField()
class Meta:
ordering = ['title']
verbose_name = 'Tag'
verbose_name_plural = 'Tags'
def __str__(self):
return self.title

我有两个视图-posts_index显示所有帖子,single应该显示单个帖子。

from django.shortcuts import render
from .models import Post, Category, Tag

def posts_index(request):
all_posts = Post.objects.all()
return render(request, 'index.html', {'posts': all_posts})

def single(request, slug, category):
single_post = Post.objects.get(slug=slug)
return render(request, 'single.html', {'single': single_post, 'category_slug': single_post.slug})

在muurls.py中,我有以下配置:

from django.urls import path
from . import views
urlpatterns = [
path('', views.posts_index, name='index'),
path('<slug:category_slug>/<slug>/', views.single, name='single')
]

我添加了几个类别(General,Sports…(,它们的后缀与标题相同,但小写,即General,Sports。

我想实现这一点,当我点击索引页面上的帖子标题时(我已经在模板中整理好了(,我会被转移到一个单独的博客文章页面,网址如下:example.com/category-slug/my-post-lug

目前,我收到这个错误:

TypeError at /general/test-post-we-hope-best/
single() got an unexpected keyword argument 'category_slug'
Request Method:     GET
Request URL:    http://127.0.0.1:8000/general/test-post-we-hope-best/
Django Version:     3.0.5
Exception Type:     TypeError
Exception Value:    
single() got an unexpected keyword argument 'category_slug'
Exception Location:     /Users/XXXXX/XXXXXXX/lib/python3.8/site-packages/django/core/handlers/base.py in _get_response, line 113

这是一个index.html模板,看起来和工作都很好,但当我点击链接时,它会抛出一个我粘贴在上面的错误。

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
{% for post in posts %}
<a href="{% url 'single' post.category.slug post.slug%}"><h2>{{post.title}}</h2></a>
<p>Posted in: {{post.category}}, Posted by: {{post.author}}</p>
<img height="120px" width="120px" src="{{post.image.url}}" alt="{{post.title}}">
<p>{{post.excerpt}}</p>
{% endfor %}
</body>
</html>

如果有任何帮助,我将不胜感激,我已经在这个问题上呆了一段时间了。

谢谢!

{% url 'single' post_id %}

如果你有两个碎片

{% url 'single' post_id, another_id %}

我会为你做这件事,但我建议把url名称改成post_details之类的东西。

那里-我自己能弄清楚,现在是视图函数:

def single(request, slug, category_slug=None):
single_post = Post.objects.get(slug=slug)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
return render(request, 'single.html', {'single': single_post, 'category_slug':category_slug})

在你的url.py中,你只需将其作为一个参数传递,如下所示:

urlpatterns = [
path('', views.posts_index, name='index'),
path('<slug:category_slug>/<slug>/', views.single, name='single')
]

最新更新