我遇到了网址问题。我想这是因为我的blog.urls'或者href是我的' models.py'。但我不知道如何改变它。我是程序员初学者。很抱歉这个问题太简单了。
问题是:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/posts.category.get_absolute_url
Using the URLconf defined in djangotest.urls, Django tried these URL patterns, in this order:
admin/
blog/ [name='list_of_post']
blog/ <slug:slug>/ [name='post_detail']
blog/ category/<slug:slug>/ [name='list_of_post_by_category']
The current path, blog/posts.category.get_absolute_url, didn't match any of these.
博客/网址:
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns =[
path('',views.list_of_post,name='list_of_post'),
path('<slug:slug>/',views.post_detail,name='post_detail'),
path('category/<slug:slug>/',views.list_of_post_by_category,name='list_of_post_by_category')
]
list_of_post.html:
{% extends 'blog/post/base.html' %}
{% block title %}List of blog post{% endblock %}
{% block content %}
{% for posts in post %}
<h2><a href="{{posts.get_absolute_url}}">{{ posts.title }}</a></h2>
<p>Written by {{ posts.author }} on {{ posts.published}} in <a href="posts.category.get_absolute_url">{{posts.category}}</a></p>
<hr>
{{ posts.content | truncatewords:40 | linebreaks}}
{% endfor %}
{% endblock %}
model.py:
class Category(models.Model):
name = models.CharField(max_length = 250)
slug = models.SlugField(max_length=250,unique=True)
class Meta:
ordering = ['name']
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_absolute_url(self):
return reverse('blog:list_of_post_by_category',args=[self.slug])
def __str__(self):
return self.name
答案 0 :(得分:2)
由于posts.category.get_absolute_url
是一个变量,因此必须将其括在花括号内:
<a href="{{posts.category.get_absolute_url}}">{{posts.category}}</a>
此外,{% for posts in post %}
看起来很奇怪。您是否从视图中传递了post
的帖子列表?我建议将其posts
,条件将更改为{% for post in posts %}