如果我有一個url爲「someurl/report/1 /」,其中「report」是一個應用程序,「1」對應於我的SQL數據庫中某個模型的某個ID ,我將如何用該特定模型數據替換模板中的變量?根據Django中的url使用不同的SQL數據
在我的情況下,我正在寫一個網站,顯示不同海灘的衝浪報告。我已經設置好了,因此每個SQL模型ID都對應不同的海灘。因此,如果我想在模板中使用海灘「3」的數據,我將如何在html模板中顯示這些數據?
TRACEBACK
使用在surfsite.urls定義URL配置,Django的嘗試了這些URL模式,在該順序: ^管理員/ ^報告/^$ [名= '索引'] ^報告/( ?P [0-9] +)$ [name ='get_report'] 當前網址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})
刪除網址中加入空格行沙灘=海灘.objects.get(id = id)是獲得th的過濾器從URL確切的海灘正確? –
是的,你在請求中獲得ID –
那麼,我將如何訪問風變量,例如,在模板中? –