当我点击django上的链接时,我收到错误404,我花了很多时间试图看看我做错了什么但没有运气。
这是我的index.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>{{title}}</h1>
{% for obj in object_list %}
{% url "detail" id=obj.id %}
<a href = '{{obj.get_absolute_url}}'> {{obj.title}}</a><br/>
{{obj.content}} <br/>
{{obj.timestamp}} <br/>
{{obj.updated}} <br/>
{{obj.id}} <br/>
{% endfor %}
</body>
</html>
这是我的urls.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
post_list,
post_create,
post_detail,
post_update,
post_delete,
)
urlpatterns = [
url(r'^$', post_list),
url(r'^create/$', post_create),
url(r'^detail/(?P<id>\d+)/$', post_detail, name='detail'),
url(r'^update/$', post_update),
url(r'^delete/$', post_delete),
]
这是我的views.py
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.
def post_create(request):
return HttpResponse("<h1>Create</h1>")
def post_detail(request, id): # retreive
instance = get_object_or_404(Post, id=id)
context = {
"title": instance.title,
"instance": instance,
}
return render(request, "post_detail.html", context)
def post_list(request): # list of posts
queryset = Post.objects.all
context = {
"title": "List",
"object_list": queryset,
}
return render(request, "index.html", context)
def post_update(request):
return HttpResponse("<h1>Update</h1>")
def post_delete(request):
return HttpResponse("<h1>Delete</h1>")
这是我的models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length = 120)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add = False )
timestamp = models.DateTimeField(auto_now=False, auto_now_add = True )
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self):
return "/posts/%s" %(self.id)
答案 0 :(得分:1)
您的get_absolute_url
方法会返回/posts/<id>
格式的网址,但您的网址预计会/posts/detail/<id>
。
您应该使用reverse
功能,而不是对方法中的URL进行硬编码:
from django.urls import reverse
...
def get_absolute_url(self):
return reverse('detail', kwargs={'id': self.id})