Issue
I am starting on my journey with Django but have hit a problem with it showing variables. In principle I want a list of buildings from which I have a Home page that shows a list of all of them as links that take you to an page that shows the detail of each one.
in models.py I have:
class Build(models.Model):
building_name = models.CharField( max_length=50)
address = models.CharField(max_length = 100)
#other details
in views.py I have:
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from .models import Build
def home(request):
builds = Build.objects.all()
return render(request, 'Home.html', {'builds':builds,})
def building_detail(request,build_id):
#return HttpResponse(f'<p> building number {build_id}</p>')
build = get_object_or_404(Build, id=build_id),
return render(request, 'Building_detail.html', {'build':build,})
In URLs.py I have:
from django.contrib import admin
from django.urls import path
from Buildings import views
urlpatterns.py = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('buildings/<int:build_id>/', views.building_detail, name= 'building_detail'),
]
For the Home.html file I have:
<p>Home view from template</p>
<div>
{% for build in builds %}
<div class="buildingname">
<a href="{% url 'building_detail' build.id %}">
<h3>{{build.building_name|capfirst}}</h3>
</a>
</div>
{% endfor %}
</div>
and for Building_detail.html this
<div>
<h3>{{build.building_name|capfirst}}</h3>
<p>building view from template is this working</p>
<h3>does this {{build.building_name|capfirst}} work</h3>
<p>{{build.address}}
</div>
the Home page works fine a shows a list of all the buildings in the database. Each one is a link to a Bulding_detail page but the building detail page only shows:
building view from template is this working
does this work
I have added the #return HttpResponse(f'
building number {build_id}
') bit to views to test thing and swapping that section in works fine, displaying the right building number. In the Building_detail.html file, I have several versions of the variables I want shown to try different thing but none have workedWhat have I done wrong or missed?
Solution
Remove the trailing comma, otherwise you are wrapping the result in a singleton tuple:
def building_detail(request, build_id):
# return HttpResponse(f'<p> building number {build_id}</p>')
build = get_object_or_404(Build, id=build_id) # 🖘 no comma
return render(
request,
'Building_detail.html',
{
'build': build,
},
)
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.