Front Facing Django Django.How

Author avatar wrote on 26/05/2022

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

  1. Import model from .models import Listing

  2. Save data from DB into an object listings = Listing.objects.all()

  3. 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

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

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.

  1. Add the app to the INSTALLED_APPS in the settings.py file ‘django.contrib.humanize’,

  2. load it in HTML file you want to use {% load humanize %}

  3. Use it {{listing.price | intcomma}}