【发布时间】:2017-05-08 15:22:44
【问题描述】:
如果我的 url 是“someurl/report/1/”,其中“report”是一个应用程序,“1”对应于我的 SQL 数据库中某个模型的 id,我将如何替换具有特定模型数据的模板?
就我而言,我正在编写一个显示不同海滩冲浪报告的网站。我已将其设置为每个 SQL 模型 ID 对应于不同的海滩。那么如果我想在模板中使用海滩“3”的数据,我将如何在html模板中显示这些数据?
追溯
使用 surfsite.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式: ^管理员/ ^report/ ^$ [名称='索引'] ^report/ (?P[0-9]+)$ [name='get_report'] 当前的 URL,report/1/,与其中任何一个都不匹配。
#URLS.PY
from django.conf.urls import url
from django.conf.urls.static import static
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
# /report/
url(r'(?P<beach_id>[0-9]+)$', views.get_report, name='get_report'),
]
#MY TEMPLATE
<!DOCTYPE html>
<html>
{% load staticfiles %}
<link rel="stylesheet" type="text/css"
href="{% static 'report/css/style.css' %}"/>
<link href="https://fonts.googleapis.com/css?family=Biryani:300,400,800"
rel="stylesheet"/>
<head>
<title>REALSURF</title>
</head>
<body>
<h1>
<form id="search">
<input id="search" type="text">
</form>
</h1>
<div class="container">
<div class="column">
<div class="text">Wind</div>
<div class="number">{{Break.wind}}</div>
</div>
<div class="column">
<div class="text">Wave Height</div>
<div class="number">{{Break.low}}-{{Break.high}}</div>
</div>
<div class="column">
<div class="text">Tide</div>
<div class="number">{{Break.tide}}</div>
</div>
</div>
<h2>
REALSURF
</h2>
<h3>
A simple site by David Owens
</h3>
</body>
</html>
#MY MODEL
from __future__ import unicode_literals
from django.db import models
class Beach(models.Model):
name = models.CharField(max_length=50)
high = models.SmallIntegerField()
low = models.SmallIntegerField()
wind = models.SmallIntegerField()
tide = models.DecimalField(max_digits=3, decimal_places=2)
def __str__(self):
return self.name
#MY VIEWS
from django.http import Http404
from django.shortcuts import render
from .models import Beach
def index(request):
allBeaches = Beach.objects.all()
context = {
'allBeaches': allBeaches,
}
return render(request, 'report/index.html', context)
def get_report(request, id):
try:
beach = Beach.objects.get(id=id)
except Beach.DoesNotExist:
raise Htpp404("404")
return render(request, 'report/index.html', {'beach': beach})
【问题讨论】: