【发布时间】:2021-09-06 11:07:17
【问题描述】:
我已经完成了 Django 教程的所有部分,现在已经开始我自己的项目来练习。我回到了it talks about views/mapping urls 的开始教程。我也在关注this tutorial for trying to display a table
无论出于何种原因,我无法弄清楚为什么当我尝试点击http://127.0.0.1:8000/show/ 时,它会返回 404。我在过去的一个小时里一直在盯着这个,并且一直在教程和我的代码之间来回切换。我必须做的事情与第二个提到的教程有些不同,主要是他们没有谈论创建应用程序级 urls.py 文件。到目前为止,一切都运行良好。 models.py 文件在 MySQL 数据库中创建了表,正如我在工作台中看到的那样。
我的项目结构是这样的:
- 我的网站(项目)
- 显示数据(应用)
这是位于 mywebsite 文件夹中的项目级 urls.py 文件:
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls),
path('displaydata/', include('displaydata.urls'))
]
这是位于 displaydata 文件夹中的应用级 urls.py 文件:
from django.urls import path
from . import views
app_name = 'displaydata'
urlpatterns = [
path('', views.show, name='show')
]
这是我的 displaydata views.py 文件:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Shipment
# Create your views here.
def show(request):
shipments = Shipment.objects.all()
return HttpResponse(render(request,"show.html",{'shipment':shipments}))
这里是 show.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Django CRUD Operations</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Shipment ID</th>
<th>Driver</th>
<th>Destination City</th>
<th>Destination State</th>
</tr>
</thead>
<tbody>
{% for ship in shipment %}
<tr>
<td>{{ship.id}}</td>
<td>{{ship.driver}}</td>
<td>{{ship.destination_city}}</td>
<td>{{ship.destination_state}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
【问题讨论】:
标签: python django django-urls