我正在尝试用 Django 创建博客。我需要将主页中的帖子映射到帖子页面。为此,我在 models.py 中定义了一个名为get_absulute_url(self)的函数,但它在 index.html 中无法识别。当我点击链接时没有任何反应......我不知道我在哪里犯了错误!
模型.py
from django.db import models
from django.urls import reverse
import posts
# Create your models here.
class post(models.Model):
title=models.CharField(max_length=500)
content=models.TextField()
timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)
updated= models.DateTimeField(auto_now=False,auto_now_add=True)
def get_absulute_url(self):
return reverse("posts:detail", kwargs={'id': self.id})
# return reverse(viewname=posts.views.posts_list,urlconf=any, kwargs={"id": self.id})
视图.py
def posts_list(request):#list items
queryset=post.objects.all()
context={
"objectsList":queryset,
"title":"list"
}
return render(request,"index.html",context)
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for obj in objectsList %}
<a href="{{ obj.get_absulute_url }}">Link</a><br>
<a href="{% url "posts:detail" id=obj.id %}">{{ obj.title }}</a> <br>
{{ obj.content }} <br>
{{ obj.timestamp }} <br>
{{ obj.updated }} <br>
{{ obj.id }} <br>
{{ obj.pk }} <br>
{% endfor %}
</body>
</html>
网址.py
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('create/',posts_views.posts_create),
path('<int:id>/', posts_views.posts_detail,name="detail"),
path('',posts_views.posts_list),
path('update/', posts_views.posts_update),
path('delete/', posts_views.posts_delete),
]
森林海
慕森王
相关分类