找不到页面:/<int:pk>.pk

时间:2019-01-09 16:50:54

标签: python django

有人可以告诉我,为什么通过链接模板链接生成的URL是/.pk。我试图了解网址的工作方式。这里是Django的新手。

Traceback (most recent call last):
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 647, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 357, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 717, in __init__
    self.handle()
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle
    handler.run(self.server.get_app())
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
Not Found: /<int:pk>.pk
[10/Jan/2019 00:18:34] "GET /%3Cint:pk%3E.pk HTTP/1.1" 404 16594

模板

<h1><a href="{% url 'details' pk=Testimony.id %}">{{testimony.Title}}</h1>

urls.py

urlpatterns = [
  ...
    path('<int:pk>/$', views.detail, name='details'),
]

views.py

def details(self, pk):
    print('1')
    testimony=get_object_or_404(Testimony, pk= pk)
    print('2')
    return render(request, 'details.html', {'testimony': testimony})

1 个答案:

答案 0 :(得分:1)

就像上一个问题一样,您将path()的新语法和re_path() / url()的正则表达式语法混为一谈。

path()不使用正则表达式,因此您不应在末尾加上$。更改为:

path('<int:pk>/', views.detail, name='details'),

由于模板上下文为{'testimony': testimony},因此应在url标记中使用小写的testimony

<h1><a href="{% url 'details' pk=testimony.id %}">{{testimony.Title}}</h1>

对代码/模板进行更改后,请确保已保存所有更改并重新启动服务器,以确保您正在运行自己认为的代码。