在django 2.0.5中使用urls.py中的path()的问题

时间:2018-06-08 19:09:31

标签: python django

我正在按照我在Django 2.0.5中尝试编写的教程,但是我在urls.py中遇到了障碍,而且我已经搜索了一周,但仍然给了我一页未找到(404)错误消息。 有人可以更清楚地了解path(),因为它似乎不支持正则表达式。 这是我的代码:

views.py

from django.shortcuts import render
#from django.http import HttpResponse
from .models import Board

# Create your views here.

模板/ topics.html

    {% load static %}<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
      <title>{{board.name}}</title>
      <link rel="stylesheet" type="text/css" href="{% static 
       'css/bootstrap.min.css' %}">>
    </head>
    <body>
     <div class="container">
        <ol class="breadcrumb my-4">
            <li class="breadcrumb-item">Boards</li>
            <li class="breadcrumb-item active">{{board.name}}</li>
        </ol>
     </div>

    </body>
    </html>

urls.py

   from django.contrib import admin
   from django.urls import path

   from boards import views


   urlpatterns = [
    path('', views.home, name='home'),

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

    path('admin/', admin.site.urls)

]

models.py

   from django.db import models
   from django.contrib.auth.models import User

   # Create your models here.

   class Board(models.Model):
      name = models.CharField(max_length=30, unique=True)
      description = models.CharField(max_length=100)

     def __str__(self):
         return self.name


   class Topic(models.Model):
      subject = models.CharField(max_length=255)
      last_updated = models.DateTimeField(auto_now_add=True)
      board = models.ForeignKey(Board, on_delete=models.CASCADE)
      starter = models.ForeignKey(User, on_delete=models.CASCADE)


    # def __str__(self):
    #   return self.subject


  class Post(models.Model):
      message = models.TextField(max_length=4000)
      topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
      created_at = models.DateTimeField(auto_now_add=True)
      updated_at = models.DateTimeField(null=True)
      created_by = models.ForeignKey(User, on_delete=models.CASCADE)
      #updated_by = models.ForeignKey(User, null=True)

  #   def __str__(self):
        # return self.subject

和浏览器中的错误消息

   Page not found (404)
   Request Method:  GET
   Request URL: http://127.0.0.1:8000/board/1/
   Using the URLconf defined in myproject.urls, Django tried these URL patterns, 
   in this order:

   [name='home']
   <int:pk>/ [name='board_topics']
   admin/
   The current path, board/1/, didn't match any of these.

   You're seeing this error because you have DEBUG = True in your Django 
   settings file. Change that to False, and Django will display a standard 404 
   page.

1 个答案:

答案 0 :(得分:1)

您尚未定义与'/board/<pk>/'匹配的网址。如果你想将urls.py文件中当前的board_topics作为该网址,那么它应该是'board/<int:pk>/',而不仅仅是'<int:pk>/'