I'm building a site in Django but I'm kind of stuck with the following problem.
In my home.html I have a list which looks something like this:
{% extends "main/header.html" %}
{% block content %}
<body>
<div class="itemlist">
<ul>
<li><a href="item1">Item 1</a></li>
<li><a href="item2">Item 2</a></li>
<li><a href="item3">Item 3</a></li>
<li><a href="item4">Item 4</a></li>
</ul>
</div>
</body>
{% endblock %}
This list is updated dynamically, so there will be more and different items
.
This is what I'm trying to do: for each of those items, when I open the item's link, a new page should be opened, containing data about the item, like this: site.com/item1, or site.com/item2
The problem: I can't create a view and a template for each item since the list will grow. Creating a view, a template and a url for each is not a doable solution.
A possible approach: create a view that generates a standard page and append the link to that page, like this:
site.com/items/item-here
, so for example site.com/items/item15
The problem is that I'm fairly new to Django, so I don't know how to apply this approach practically.
Can someone give me a hint on where I should go from here? Every advice is appreciated. I hope my problem was understandable.
You could use FBVs. One view and one template required.
Views.py:
from django.shortcuts import get_object_or_404, render
def render_items(request, item_name):
item = get_object_or_404(YOUR_MODEL, YOUR_ITEM_FIELD_NAME=item_name)
return render(request, 'YOUR_TEMPLATE.html', {'item': item })
Add below line to urlpatterns
path('items/<str:item_name>/',views.render_items, name='item'),
Detail Template
{% extends "main/header.html" %}
{% block content %}
<body>
<div class="item-detail">
<h1> Detail </h1>
<p>{{ item.name }}</p>
</div>
</body>
{% endblock %}