Вывести атрибуты класса на страницу
Есть класс:
class Product():
def __init__(self, id, name):
self.id = id
self.name = name
self.category = "category"
self.animal = "animal"
self.count = 33
self.price = 1299
Хочу вывести его атрибуты на страницу, но у меня не получается. Что я делаю не так?
views.py:
def class_1(request):
pet = Product(1, 'cat')
context = {
'id': pet.id,
'name': pet.name,
'category': pet.category,
'count': pet.count,
'price': pet.price
}
return render(request, 'index.html', context)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if id %}
<h1>ID: {{id}}</h1>
{% endif %}
</body>
</html>
Функция views
и шаблоне HTML.
views.py
:
from django.shortcuts import render
class Product():
def __init__(self, id, name):
self.id = id
self.name = name
self.category = "category"
self.animal = "animal"
self.count = 33
self.price = 1299
def class_1(request):
pet = Product(1, 'cat')
context = {
'id': pet.id,
'name': pet.name,
'category': pet.category,
'animal': pet.animal,
'count': pet.count,
'price': pet.price
}
return render(request, 'index.html', context)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>ID: {{id}}</h1>
<p>Name: {{name}}</p>
<p>Category: {{category}}</p>
<p>Animal: {{animal}}</p>
<p>Count: {{count}}</p>
<p>Price: {{price}}</p>
</body>
</html>
Возможно ошибка в Вашем urls.py. Должен выглядеть примерно так:
from django.urls import path
from .views import class_1
urlpatterns = [
path('', class_1, name='index'),
]