Showing the Database’s content on the Front Facing
n view.py under index function, get the list of question and store them in an object then pass them to the url
-
Import model from .models import Listing
-
Save data from DB into an object listings = Listing.objects.all()
-
Create the dictionary to pass to the template
context = {
'listings' : listings
}
4. Pass the context return render(request, ‘listings/listings.html’, context)
5. Use the data in template {{ listing.listing.title }}
6. Show many rows use for loop
{% endfor %}
{% else %}
No Listings
{% endif %}
Linking to a Single Record
The id must be passed in the html link, urls.py, and views.py
1. In the HTML file you want to use
2. In urls.py
path('', views.listing, name='listing'),
3. In views.py
def listing(request, listing_id):
return render(request, 'listings/listing.html')
Example
from django.shortcuts import render
from .models import Listing
def index(request):
listings = Listing.objects.all()
context = {
'listings' : listings
}
return render(request, 'listings/listings.html', context)
Edit the HTML file
{% block content %}
{% if listings %}
{% for listing in listings %}
{{ listing.title}}
{{listing.city}} {{listing.state}}, {{listing.zapcode}}
{% endfor %}
{% else %}
No Listings
{% endif %}
Important Tools
Humanize makes make number looks better https://docs.djangoproject.com/en/3.0/ref/contrib/humanize/
-
apnumber 1 becomes one.
-
intcomma 1000000 to become 1,000,000
-
intword 1000000 becomes 1.0 million.
-
naturalday 16 Feb 2007 becomes yesterday. Assuming today is 17 Feb 2007
-
naturaltime17 Feb 2007 16:29:31 becomes 29 seconds ago.
-
Add the app to the INSTALLED_APPS in the settings.py file ‘django.contrib.humanize’,
-
load it in HTML file you want to use {% load humanize %}
-
Use it {{listing.price | intcomma}}