我是一个完整的初学者,因此我为我的肥胖解释表示歉意。我正在对博客进行分类。
我创建了一个模型->迁移了它->在view.py中导入->将我创建的视图导入urls.py->并为新页面创建了URL,但是当我将href添加到其他页面时(首页)将我带到错误状态。
我的代码: models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, default='Engineering')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Views.py:
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name= 'blog/category_posts.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
urls.py:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
home.html
<a href="{% url 'category-posts' %}">{{ post.category }}</a>
答案 0 :(得分:0)
您还应该像这样在URL中传递类别
<a href="{% url 'category-posts' post.category %}">{{ post.category }}</a>
因为您的网址需要一个str参数类别。
答案 1 :(得分:0)
除了阿伦所说的。
我认为您需要在urls.py中设置url_patters
。像这样:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
urlpatterns = [
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
]