Answer the question
In order to leave comments, you need to log in
When I go to a post, I can’t get data from the database for this particular post, how to implement it?
I display all the records that are in the database on the site. When I go to the link, a link is generated based on the ID.
But on the post page, I can’t get data from the database for this particular post.
URLs
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', ListView.as_view(queryset=AllFilms.objects.all().order_by("-date")[:12], template_name="main/homepage.html")),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model = AllFilms, template_name="main/post.html"))
]
def index(request):
posts = AllFilms.objects.all()
return render(request, 'main/homepage.html', context = {'posts' : posts})
{% extends "main/wrapper.html" %}
{% block content %}
<a>{{ film.title }}</a>
{% endblock %}
Answer the question
In order to leave comments, you need to log in
In general, use class based veiws, that is, class-based views. Here I will give an example of displaying a list of books (without inheritance from ListView, in order to better understand how it works). Suppose these books will be cards in the template and each card has a button to go to that book.
In the model class, you need to define the get_absolute_url method. At the end of the answer, you will understand why.
models.py
See the documentation for what reverse is.
class Book(models.Model):
title = models.CharField(...)
...
def get_absolute_url(self):
return reverse("book-detail-page-url", args=[str(self.id)]
urlpatterns = [
path("books/", BooksListView().as_view(), name="books-page-url"),
path("book/<id>/", BookDetailView().as_view(), name="book-detail-page-url")
]
class BookListView(View):
def get(self, request):
books = Book.objects.all()
return render(request, "books.html", context={"books": books})
class BookDetailView(View):
def get(request, id):
book = Book.objects.filter(id=id)
return render(request, "book_detail.html", context={"book": book})
...
{% for book in books %}
{{ book.title }}
...
<a href="{{ book.get_absolute_url }}" class="btn btn-primary">Подробнее</a>
...
{% endfor %}
...
{{ book.title }}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question