Pagination in Django ListView when using get_context_data - python

I am currently facing this problem with Django ListView. Basically, I need to filter some questions per topic and I would like to paginate the results.
My code is working perfectly about the queryset part (the results are showed correctly) but I am facing a problem with pagination.
Let's say I have so far 8 items in my query, if I choose to paginate_by = 10, it shows me just one page. If, otherwise, I choose to paginate by, let's say, 3, it shows me 3 pages to choose in the template (which is correct) but it shows me ALL the results of the query in my page.
I post some code to be more clear
models.py:
class Tag(models.Model):
name = models.CharField(max_length=300, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def clean(self):
self.name = self.name.capitalize()
def __str__(self):
return self.name
class Question(models.Model):
post_owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=5000, default='')
body = tinymce_models.HTMLField()
tags = models.ManyToManyField(
Tag, related_name='tags')
viewers = models.ManyToManyField(
User, related_name='viewed_posts', blank=True)
views.py:
class TagQuestionsListView(ListView):
template_name = 'main/tag_questions.html'
paginate_by = 20
def get_queryset(self, **kwargs):
tag = Tag.objects.get(name=self.kwargs['name'])
questions = Question.objects.filter(tags=tag)
return questions
def get_contextdata(self, **kwargs):
context = super().get_context_data(**kwargs)
context['tag'] = Tag.objects.get(name=self.kwargs['name'])
context['questions'] = Question.objects.filter(
tags=context['tag'], is_deleted=False)
return context
template:
{% extends 'base.html' %}
{% load humanize %}
{% block title %}Domande su {{tag.name}}{% endblock title %}
{% block content %}
<style>
.text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* number of lines to show */
line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>
<div class="card">
<div class="mt-3">
<h3 class="ms-2" style="display: inline;">Ultime {{ questions.count }} Domande</h3>
{% if request.user.is_authenticated %}
Fai una domanda
{% else %}
Fai una domanda
{% endif %}
</div>
<h5 class="ms-2">{{ total_questions.count }} domande totali </h5>
<hr>
{% for question in questions %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
</div>
<div class="row mt-3">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.previous_page_number }}">Precedente</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Precedente</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li class="page-item {% if page_obj.number == i%} active {% endif %} %} "><a class="page-link" href="?filter={{ filter }}&orderby={{ orderby }}&page={{ i }}">{{i}}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.next_page_number }}">Prossima</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Prossima</a></li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
{% endblock content %}

With this I want my comment converter to answer.
You have to use page_obj instead questions in your template.
<--! ⬇️⬇️⬇️ -->
{% for question in page_obj %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
So, if you define attribute paginate_by , than ListView(django docs) adds a paginator and page_obj to the context. To allow the users to navigate between pages, add links to the next and previous page, in your template.

Related

Django pagination not working. Object list is rendering items but not dividing into pages

I'm currently working on an e-commerce site and I'm trying to create a product list page that spans into another page after 4 items have been displayed. rendering the page doesn't produce any error but all items in the database are displayed on the same page and remains the same even after switching to another page.
Here's my views.py:
from django.shortcuts import render, get_object_or_404
from .models import Category, Item
from django.core.paginator import Paginator
def item_list(request, category_slug=None):
category = None
categories = Category.objects.all()
items = Item.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
items = items.filter(category=category)
paginator = Paginator(items, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request,
'item/list.html',
{'category': category,
'categories': categories,
'page_obj': page_obj,
'items': items})
my urls.py file:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.item_list, name='item_list'),
path('<slug:category_slug>/', views.item_list, name='item_list'),
path('<int:id>/<slug:slug>/', views.item_detail, name='item_detail'),
]
pagination snippet from the template
<nav class="d-flex justify-content-center wow fadeIn">
<ul class="pagination pg-blue">
<!--Arrow left-->
{% if page_obj.has_previous %}
Previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
Next
{% endif %}
</ul>
</nav>
and the logic that displays the products
<div class="row wow fadeIn">
<!--Grid column-->
{% for item in items %}
<div class="col-lg-3 col-md-6 mb-4">
<!--Card-->
<div class="card" style="width: 16rem; height: 25rem">
<!--Card image-->
<div class="view overlay">
<a href="{{ item.get_absolute_url }}">
{% if item.tags and item.label %}
<div class="imgHolder">
<img src="{{ item.image.url }}" class="img-fluid">
<span class="badge badge-pill {{ item.get_label_display }}-color">{{ item.tags }}</span>
</div>
{% else %}
<img src="{{ item.image.url }}" class="img-fluid">
{% endif %}
</a>
<a href="{{ item.get_absolute_url }}">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!--Card image-->
<!--Card content-->
<div class="card-body text-center" style="height: 9rem;">
<!--Category & Title-->
<a href="{{ item.category.get_absolute_url }}" class="grey-text">
<h5>{{ item.category.name|truncatechars:20 }}</h5>
</a>
<h5>
<strong style="color:red">
{{ item.name }}
</strong>
</h5>
<h6 class="font-weight-bold">
{% if item.discount_price %}
<strong><del>${{ item.price}}</del></strong>
<strong>${{ item.discount_price }}</strong>
{% else %}
<strong>${{ item.price }}</strong>
{% endif %}
</h6>
</div>
<!--Card content-->
</div>
<!--Card-->
</div>
{% endfor %}
</div>
I'd really like to know what I'm doing wrong and I'm also open to alternative means of solving the same problem. Thanks
You are using all the queryset that you are passing to the paginator. You must iterate over the page_obj.object_list.
page_obj = paginator.get_page(page_number)
page_obj_items = page_obj.object_list
you need to loop throw {% for item in page_obj %}

Problems with get_gueryset method in Django

I have a problem with filtering a queryset that after filtering should be paginated, I am using get_queryset to filter the queryset of objects but on the page nothing is displayed. I have a blog page where I have all the post in a list, and are paginated, on the page I have the most common tags and whenever I click on a tag it redirects the user on the page with posts that have that tag and I want them to be displayed in a list and to be paginated like in the initial page but it's not working.
my view:
class TaggedPostListView(ListView):
model = Post
template_name = 'blog/blog.html'
context_object_name = 'posts'
paginate_by = 2
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
tags = Post.tags.most_common()[:8]
context['banner_page_title'] = 'Blog'
context['page_location'] = 'home / blog'
context['tags'] = tags
return render(request, self.template_name, context)
def get_context_data(self, **kwargs):
context = {}
return context
def get_queryset(self):
tag = get_object_or_404(Tag, slug=self.kwargs.get('slug'))
return Post.objects.filter(tags=tag).order_by('-published_date')
model:
class Post(models.Model):
class PostCategory(models.TextChoices):
FAMILY = 'FAMILY', _('Family')
BUSINESS = 'BUSINESS', _('Business')
MWRKETING = 'MARKETING', _('Marketing')
SPENDINGS = 'SPENDINGS', _('Spendings')
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(_('Title'), max_length=200, unique=True)
content = models.TextField(_('Content'))
category = models.CharField(_('Category'), max_length=9, choices=PostCategory.choices, default=PostCategory.BUSINESS)
slug = models.SlugField(_('Slug'), max_length=200, blank=True, null=False, unique=True)
tags = TaggableManager(_('Tags'))
published_date = models.DateTimeField(_('Published Date/Time'), auto_now_add=True)
updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
#property
def comments_count(self):
return self.comments.count()
url:
path('tag/<slug:slug>/', TaggedPostListView.as_view(), name='tag'),
{% extends 'home/base.html' %}
{% load static %}
{% block content %}
<!--================Blog Area =================-->
<section class="blog_area section-margin">
<div class="container">
<div class="row">
<div class="col-lg-8 mb-5 mb-lg-0">
<div class="blog_left_sidebar">
{% for post in posts %}
<article class="blog_item">
<div class="blog_item_img">
<img class="card-img rounded-0" src="{% static 'img/blog/m-blog-1.jpg' %}" alt="Post Image">
<a href="{% url 'post' post.slug %}" class="blog_item_date">
<h3>{{ post.published_date|date:"d" }}</h3>
<p>{{ post.published_date|date:"M" }}</p>
</a>
</div>
<div class="blog_details">
<a class="d-inline-block" href="{% url 'post' post.slug %}">
<h2>{{ post.title }}</h2>
</a>
<p>{{ post.content|truncatechars:200 }}</p>
<ul class="blog-info-link">
<li><i class="ti-user"></i></li>
{% if post.comments_count %}
<li><i class="ti-comments"></i>{{ post.comments_count }} - Comments</li>
{% else %}
<li><i class="ti-comments"></i>0 Comments</li>
{% endif %}
</ul>
</div>
</article>
{% endfor %}
{% if is_paginated %}
<nav class="blog-pagination justify-content-center d-flex">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous">
<span aria-hidden="true">
<span class="ti-arrow-left"></span>
</span>
</a>
</li>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<li class="page-item active">
{{ num }}
</li>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<li class="page-item">
{{ num }}
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="ti-arrow-right"></span>
</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</div>
<div class="col-lg-4">
<div class="blog_right_sidebar">
<aside class="single_sidebar_widget search_widget">
<form action="#">
<div class="form-group">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search Keyword">
<div class="input-group-append">
<button class="btn" type="button"><i class="ti-search"></i></button>
</div>
</div>
</div>
<button class="button rounded-0 w-100" type="submit">Search</button>
</form>
</aside>
<aside class="single_sidebar_widget post_category_widget">
<h4 class="widget_title">Category</h4>
<ul class="list cat-list">
<li>
<a href="#" class="d-flex">
<p>Resaurant food</p>
<p>(37)</p>
</a>
</li>
<li>
<a href="#" class="d-flex">
<p>Travel news</p>
<p>(10)</p>
</a>
</li>
<li>
<a href="#" class="d-flex">
<p>Modern technology</p>
<p>(03)</p>
</a>
</li>
<li>
<a href="#" class="d-flex">
<p>Product</p>
<p>(11)</p>
</a>
</li>
<li>
<a href="#" class="d-flex">
<p>Inspiration</p>
<p>21</p>
</a>
</li>
<li>
<a href="#" class="d-flex">
<p>Health Care (21)</p>
<p>09</p>
</a>
</li>
</ul>
</aside>
<aside class="single_sidebar_widget popular_post_widget">
<h3 class="widget_title">Recent Post</h3>
{% for post in recent_posts %}
<div class="media post_item">
<img src="img/blog/popular-post/post1.jpg" alt="post">
<div class="media-body">
<a href="single-blog.html">
<h3>{{ post.title }}</h3>
</a>
<p>{{ post.date_posted|date:"F m, Y" }}</p>
</div>
</div>
{% endfor %}
</aside>
<aside class="single_sidebar_widget tag_cloud_widget">
<h4 class="widget_title">Post Tags</h4>
<ul class="list">
{% for tag in tags %}
<li>
{{ tag }}
</li>
{% endfor %}
</ul>
</aside>
<aside class="single_sidebar_widget instagram_feeds">
<h4 class="widget_title">Instagram Feeds</h4>
<ul class="instagram_row flex-wrap">
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i1.png" alt="">
</a>
</li>
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i2.png" alt="">
</a>
</li>
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i3.png" alt="">
</a>
</li>
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i4.png" alt="">
</a>
</li>
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i5.png" alt="">
</a>
</li>
<li>
<a href="#">
<img class="img-fluid" src="img/instagram/widget-i6.png" alt="">
</a>
</li>
</ul>
</aside>
<aside class="single_sidebar_widget newsletter_widget">
<h4 class="widget_title">Newsletter</h4>
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" name="newsletter_email" placeholder="Enter email" required>
</div>
<button class="button rounded-0 w-100" type="submit">Subscribe</button>
</form>
</aside>
</div>
</div>
</div>
</div>
</section>
<!--================Blog Area =================-->
{% endblock %}
The problem is not get_queryset, the problem is that get_context_data, the method that is supposed to produce a dictionary that contains the context variables, no longer can work properly because you let it return an empty dictionary. You simply should override it, and add the items you want to pass to the template:
class TaggedPostListView(ListView):
model = Post
template_name = 'blog/blog.html'
context_object_name = 'posts'
paginate_by = 2
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
tags = Post.tags.most_common()[:8]
context['banner_page_title'] = 'Blog'
context['page_location'] = 'home / blog'
context['tags'] = tags
return context
def get_queryset(self):
tag = get_object_or_404(Tag, slug=self.kwargs.get('slug'))
return Post.objects.filter(tags=tag).order_by('-published_date')
In the template, you need to enumerate over the page_obj if you want to paginate, so:
{% for post in page_obj %}
# …
{% endfor %}

Django paginator issue

I am currently working on a django blog and I've coded a search bar where you type something and, if there's any post that contains what you've typed in the title, it should appear all the posts. This part is perfectly well-written. However, there's an error with the pagination. As you'll see in the views.py. The maximum num of posts per page is 3. However, you can see there's four. However, the paginator detects there should be another page for the fourth posts. Here's an image that shows that.
Here's the views.py:
class ElementSearchView(View):
elements_list = Element.objects.all()
def get(self, request, *args, **kwargs):
paginator = Paginator(self.elements_list, 3)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
queryset = Element.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(
Q(title__icontains=query)
).distinct()
context = {
'query': queryset,
'queryset': paginated_queryset,
'page_request_var': page_request_var,
}
return render(request, 'periodic/search_results_table.html', context)
And here's the html template: The pagination is at the end of the template.
{% load static %}
<html>
{% include 'periodic/head_search.html' %}
<body>
{% include 'periodic/header.html' %}
<br>
<br>
<div class="container">
<div class="row">
<!-- Latest Posts -->
<main class="posts-listing col-lg-8">
<div class="container">
<div class="row">
<!-- post -->
{% for element in query %}
<div class="post col-xl-6 wrap-login100">
<div class="post-thumbnail"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<a href="{{ element.get_absolute_url }}">
<h3 class="h4">{{ element.title }}</h3></a>
</div>
</div>
{% endfor %}
</div>
<!-- Pagination -->
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if queryset.has_previous %}
<li class="page-item"> <i class="fa fa-angle-left"></i></li>
{% endif %}
<li class="page-item">{{ queryset.number }}</li>
{% if queryset.has_next %}
<li class="page-item"> <i class="fa fa-angle-right"></i></li>
{% endif %}
</ul>
</nav>
{% if is_paginated %}
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item"> <i class="fa fa-angle-left"></i></li>
{% endif %}
<li class="page-item">{{ page_obj.number }}</li>
{% if page_obj.has_next %}
<li class="page-item"> <i class="fa fa-angle-right"></i></li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</main>
</body>
{% include 'periodic/scripts_search.html' %}
</html>
As the user #ikilnac mentioned,
you are looping over the original queryset and not the paged one in your template
That simply means that in your loop, you do this
{% for element in query %}
<div class="post col-xl-6 wrap-login100">
<div class="post-thumbnail"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<a href="{{ element.get_absolute_url }}">
<h3 class="h4">{{ element.title }}</h3></a>
</div>
</div>
{% endfor %}
And then after that, you are using the tag in the form of {% if queryset.has_previous %} with the original queryset rather than the paged one in the template (the query).
There's a good example of it here - Paginate with Django

Django: Using a loop to output images and text from the db

I'm learning programming and following a tutorial using django 3, the same I'm using.
The text and images are not displaying on the frontend on one particular html file.
1.-In settings.py I have this:
MEDIA_ROOT= os.path.join(BASE_DIR,"media")
MEDIA_URL= "/media/"
2.-In models.py:
class Property(models.Model):
title = models.CharField(max_length=200)
main_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
3.-In admin.py:
from django.contrib import admin
from .models import Property
class PropertyAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'is_published')
list_display_links = ('id', 'title')
search_fields = ('title', 'town')
list_editable = ('is_published',)
list_per_page = 30
admin.site.register(Property, PropertyAdmin)
Then I migrated to the DB, I created a properties.html and the loop {{ property.main_photo.url }} or {{ property.title }} is working and getting images and texts on this properties file:
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Browse Our Properties</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur!</p>
</div>
</div>
</div>
</section>
<!-- Listings -->
<section id="listings" class="py-4">
<div class="container">
<div class="row">
{% if properties %}
{% for property in properties %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<img class="card-img-top" src="{{ property.main_photo.url }}" alt="">
<div class="card-img-overlay">
<h2>
<span class="badge badge-secondary text-white">From {{ property.price_per_week | intcomma }}€ per week</span>
</h2>
</div>
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ property.title }}</h4>
<p>
<i class="fas fa-map-marker text-secondary"></i> {{ property.town }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-check"></i> {{ property.swimming_pool }}</div>
<div class="col-6">
<i class="fas fa-wifi"></i> {{ property.free_wifi }}</div>
</div>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-bed"></i> Bedrooms: {{ property.bedrooms }}</div>
<div class="col-6">
<i class="fas fa-bath"></i> Bathrooms: {{ property.bathrooms }}</div>
</div>
More Info
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>No Properties available</p>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-md-12">
{% if properties.has_other_pages %}
<ul class="pagination">
{% if properties.has_previous %}
<li class="page-item">
<a href="?page={{properties.previous_page_number}}" class="page-link">«
</a>
</li>
{% else %}
<li class="page-item-disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in properties.paginator.page_range %}
{% if properties.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
{% endblock %}
The next step is to create a property.html file and also use loop, but everything that uses the loop doble curly braces are not displaying:
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">{{ property.title }}</h1>
<p class="lead">
<i class="fas fa-map-marker"></i> {{ property.town }}</p>
</div>
</div>
</div>
</section>
{% endblock %}
I checked multiple times and my code is exactly like on the tutorial but my frontend is not displaying.
Views.py:
from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .models import Property
def index(request):
properties = Property.objects.get_queryset().order_by('id').filter(is_published=True)
paginator = Paginator(properties, 30)
page = request.GET.get('page')
paged_properties = paginator.get_page(page)
context = {
'properties': paged_properties
}
return render(request, 'properties/properties.html', context)
def property(request, property_id):
property = get_object_or_404(Property, pk=property_id)
context = {
'property': property
}
return render(request, 'properties/property.html')
def search(request):
return render(request, 'properties/search.html')
You are not passing the context to properties/property.html inside def property(..., ...)
Change:
return render(request, 'properties/property.html')
To:
return render(request, 'properties/property.html', context)

How to post data from google books API to your Book model using Django

I know this is my first question and I wouldn't be like writing it here, but I have a problem which I couldn't handle for 2 days now.
I am writing an app in Django, and my goal is to handle requests from google books API and display books in the template which I did.
I wrote a function like this
services.py
from googleapiclient.discovery import build
import json
def get_books_data(query):
"""Retriving data from google books API"""
service = build('books',
'v1',
developerKey=API_KEY
)
request = service.volumes().list(q=query)
response = request.execute()
book_list = [response['items'][item]['volumeInfo']
for item in range(len(response['items']))]
return book_list
I get a list of key: value pairs representing ten books from API.
I passed them into a template like this
views.py
def search(request):
query = request.GET.get('q')
books = get_books_data(query)
context = {
'books': books
}
return render(request, 'books_list.html', context)
This is how book_list.html looks like.
list_book.html
{% extends 'base.html' %}
{% load static %}
{% block content%}
{% for book in books %}
<div class="row">
<div class="col-lg-8 mx-auto">
<ul class="list-group shadow">
<li class="list-group-item">
<div class="media align-items-lg-center flex-column flex-lg-row p-3">
<div class="media-body order-2 order-lg-1">
<h5 class="mt-0 font-weight-bold mb-2">{{ book.title }}</h5>
<p class="font-italic text-muted mb-0 small">{{ book.subtitle }}</p>
{% for identifier in book.industryIdentifiers %}
<p class="font-italic text-muted mb-0 small">{{ identifier.type }} : {{ identifier.identifier }}</p>
{% endfor %}
<p class="font-italic text-muted mb-0 small">Language: {{ book.language }}</p>
<p class="font-italic text-muted mb-0 small">Published date: {{ book.publishedDate }}</p>
<div class="media-body order-2 order-lg-1">
{% if book.authors %}
<h6 class="font-weight-bold my-2">Authors:</h6>
{% for author in book.authors %}
<p class="font-italic text-muted mb-0 small">{{ author }}</p>
{% endfor %}
{% endif %}
</div>
{% if book.pageCount %}
<div class="d-flex align-items-center justify-content-between mt-1">
<h6 class="font-weight-bold my-2">Number of pages: {{book.pageCount}}</h6>
</div>
{% endif %}
</div>
{% if book.imageLinks %}
<img class="thumbnail" src="{{book.imageLinks.thumbnail}}" alt="">
{% else %}
<img class="thumbnail2" src="{% static 'images/placeholder4.png'%}" alt="">
{% endif %}
</div>
<form action="." method="post">
{% csrf_token %}
<button type="submit" class="btn btn-primary">ADD THIS BOOK TO YOUR BOOKSHELF</button>
</form>
</li>
</ul>
</div>
</div>
{% endfor %}
{% endblock content %}
And last part of my task is to have a button in each card with a book, I can use to save a particular book from API to the database.
I am a beginner in Django, and I've tried to use forms, I've read, I could use Django Rest Framework somehow but really, I don't have an idea, how I could approach this problem.
Please, Can you help me?
Than you in advance.

Categories