Home > Mobile >  Defining view function for displaying postgres data in django
Defining view function for displaying postgres data in django

Time:12-18

I created the wines database in postgresql (containing ID, names etc), and inserted around 300 observations. I would like to display names of every wine in drop menu with django. The urls.py are properly setted up. What have I done so far:

models.py

from django.db import connection
from django.db import models

class ListWines(models.Model):
    name = models.CharField(max_length=200)

views.py

from django.shortcuts import render
from wineapp.models import ListWines

def showallwines(request):
    wines = ListWines.objects
    return render(request, 'main.html', { 'name':wines } )

main.html

<!DOCTYPE html>
<head>
    <body>
        <select>
            <option disabled = "True" selected>Select your favourite wine!</option>
            {% for wines in showallwines %}
            <option>{{wines.name}}</option>
            {% endfor %}
        </select>
    </body>
</head>

The postgres database (column containing data that I want to display is name) is connected with app by setings.py, however it doesn't show names.

How should I redefine my functions in order to see display in main.html drop menu?

CodePudding user response:

To get the list of all objects, you must use Model.objects.all()

So make these changes in your view

def showallwines(request):
    wines = ListWines.objects.all() # changed
    # changed context name to wines since it is list of wines not names.
    return render(request, 'main.html', { 'wines': wines } )

main.html

You have to use the context name wines since we are passing the context wines from the view

{% for wine in wines %}
    <option>{{ wine.name }}</option>
{% endfor %}

CodePudding user response:

views.py

Insted of ListWines.objects use ListWines.objects.all() and update context name with "showallwines" this.

def showallwines(request):
    wines = ListWines.objects.all()
    return render(request, 'main.html', { 'showallwines':wines } )
  • Related