Home > Mobile >  Django file not showing input data in actual website
Django file not showing input data in actual website

Time:05-29

I'm currently attempting to learn how to use django to build a website but my input data in the models is not showing up properly

'''

from django.db import models

class products(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class typeWork(models.Model):
    work = models.CharField(max_length = 255)
    hoursWorked = models.IntegerField()
    number_in_stock = models.IntegerField()
    daily_rate = models.FloatField()
    genre = models.ForeignKey(products, on_delete=models.CASCADE)

'''

models.py

'''

from django.urls import path
from . import views

urlpatterns = [
   path('hello/', views.hello, name='hello')
]

''' urls.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import typeWork


def hello(request):
    products2 = {typeWork.objects.all()}
    return render(request, 'index.html', {products2})

views.py is slightly altered as i was messing with it in order to try and fix it the image shows the code with no alterations and my original issue arising from that code

views.py

<table >
<thead>
    <tr>
        <th>Work</th>
        <th>Type of Work</th>
        <th>Hours needed</th>
    </tr>
</thead>
<tbody>
    {% for products2 in products%}
        <tr>
            <td>{{products2.work}}</td>
            <td>{{products2.genre}}</td>
            <td>{{products2.hoursWorked}}</td>
        </tr>
    {% endfor %}
    
</tbody>

indes.html is also slightly altered the image will show the original code before i tried fixing it again index.html

Actual error and what it does show currently

CodePudding user response:

You can try passing your products2 variable through a so-called "context dictionary".

Updated version of views.py: I'm currently attempting to learn how to use django to build a website but my input data in the models is not showing up properly

from django.shortcuts import render
from django.http import HttpResponse
from .models import typeWork


def hello(request):
    products2 = typeWork.objects.all()
    context = {"products2": products2}
    return render(request, 'index.html', context)

You had some idea on how to pass these variables when you put the {} symbols, but only adding names between these symbols will pass a set. A dictionary would mean the curly braces a set of key-value pairs.

The main idea is, everytime you're trying to pass data to a view, you'll need to do it via a dictionary. The key you're using will also be used in the template. By replacing your code with the one I wrote, you're going to be okay because your template is iterating through something called products2.

  • Related