How to call in the google books API in django? - python

The books are being displayed but when i click on the link it does not lead to the google books.co.in webpage where the book is stored, it displays that the page is not found.
my views.py
def books(request):
if request.method == "POST":
form=DashboardForm(request.POST)
text=request.POST['text']
url="https://www.googleapis.com/books/v1/volumes?q="+text
r = requests.get(url)
answer = r.json()
result_list = []
for i in range(10):
result_dict = {
'title':answer['items'][i]['volumeInfo']['title'],
'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'),
'description':answer['items'][i]['volumeInfo'].get('description'),
'count':answer['items'][i]['volumeInfo'].get('pageCount'),
'categories':answer['items'][i]['volumeInfo'].get('categories'),
'rating':answer['items'][i]['volumeInfo'].get('pageRating'),
'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'),
'preview':answer['items'][i]['volumeInfo'].get('previewLinks')
}
result_list.append(result_dict)
context={
'form' : form,
'results' :result_list
}
return render(request,'dashboard/books.html',context)
else:
form=DashboardForm()
context={'form' : form}
return render(request,'dashboard/books.html',context)
my books.html template
{% extends 'dashboard/base.html' %}
{% load static %}
{% block content %}
<section class='text-center container'>
<h2><b>SEARCH FOR BOOKS </b></h2>
<p>Enter the search query to obtain your desired book</p><b></b>
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-danger" type="submit" value="Submit">
</form><br>
{% for result in results %}
<a href="{{result.preview}}" target="_blank">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-3">
<img class="img-fluid" src="{{result.thumbnail}}" alt="">
</div>
<div class="col-md-9">
<h3 class="p-0 m-0">{{result.title}}</h3>
<b>
<u>
<h5 class="p-0 m-0">{{result.subtitle}}</h5>
</u>
</b>
{% if result.description %}
<h6 class="p-0 m-1">{{result.description}}</h6>
{% endif %}
<b>
{% if result.categories %}
<h6 class="ml-0 mt-3">Category:
{% for category in result.categories %}
{{category}}
{% endfor %}
</h6>
{% endif %}
{% if result.count %}
<h6 class="ml-0 mt-1">Pages: {{result.count}}</h6>
{% endif %}
{% if result.rating %}
<h6 class="ml-0 mt-1">Rating:{{result.rating}}</h6>
{% endif %}
</b>
</div>
</div>
</div>
</div>
</a>
{% endfor %}
<br>
</section>
{% endblock content %}
I have installed and imported requests and want to redirect to google books page when i click on the book.
enter image description here

The issue seems to be with the value of "preview" in the "result_dict" dictionary. It looks like the "previewLinks" key in the JSON response from the Google Books API does not contain a URL that can be directly accessed.
You can try it like this:
result_dict = {
...
'preview': answer['items'][I]['volumeInfo'].get('previewLinks').get('googlePlay'),
...
}

Related

Why can't select one object in django

I'm creating a ecommerce store using django And tried s many things to do this.index page is working pretty well but I want select specific product when I click .ex: when I click a shoe I want to enter shoe detail page with shoe image and all the necessary details.Here is my home page.And also I highly recommend to check my all code because you can't get any idea with only this code.github source code here.thanks dinindu
{% extends 'store/main.html'%}
{% load static %}
{% block content %}
<style>
img:hover{
opacity: 0.5;
}
</style>
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<a href="{% url 'productDetail' Product.name %}"><img
class="thumbnail" src="{{product.imageURL}}"></a>
<div class="box-element product">
<h6><strong>{{product.name}}</strong></h6>
<hr>
<button data-product="{{product.id}}" data-action="add"
class="btn btn-outline-secondary add-btn update-cart">Add to
Cart</button>
<h4 style="display: inline-block; float:
right"><strong>Rs {{product.price}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
you could do something like this, an adapt it to your project:
Views:
def product_list(request):
products = Product.objects.all()
return render(request,'list.html',{'products': products})
def product_detail(request, id):
product = Product.objects.get(id=id)
return render(request,'detail.html',{'product': product,})
urls:
path('products/', views.product_list, name='product_list'),
path('products/<int:id>/', views.product_detail, name='product_detail')
templates
list.html
{% for product in products %}
<div>
<a href="{% url 'product_detail' product.id %}">
<img src="{ product.image.url }}">
</a>
{{ product.name }}
</div>
{% endfor %}
detail.html
<div>
<img src="{{ product.image.url }}">
<h2>{{ product.name }}</h2>
<h3>{{ product.price }}</h3>
<h4>{{ product.digital }}</h4>
</div>

How to link "Searchbar" to Search view Django

I create a post_searchview :
def post_search(request):
form = SearchForm()
query = None
results = []
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
search_vector = SearchVector('title', 'body')
search_query = SearchQuery(query)
results = Post.published.annotate(
search=search_vector,
rank=SearchRank(search_vector, search_query),
).filter(search=search_query).order_by('-rank')
context = {'form': form, 'query': query, 'results': results}
return render(request, 'blog/post/search.html', context)
And i want to link that to my base.html where i have located an html code for the searchbar (look in the bottom of the file):
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<a class="navbar-brand" href="{% url 'blog:post_list' %}">
My Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarCollapse" aria-controls="navbarCollapse"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item mr-2">
<input class="form-control" type="text" placeholder="Search" aria-label="Search">
</li>
Also, now i have a search.html file to make the searchs, idk if i should delete it :
{% extends "blog/base.html" %}
{% block title %}Search{% endblock %}
{% block content %}
{% if query %}
<h1>Posts containing "{{ query }}"</h1>
<h3>
{% with results.count as total_results %}
Found {{ total_results }} result{{ total_results|pluralize }}
{% endwith %}
</h3>
{% for post in results %}
<h4>{{ post.title }}</h4>
{{ post.body|safe|truncatewords_html:5 }}
{% empty %}
<p>There are no results for your query.</p>
{% endfor %}
<p>Search again</p>
{% else %}
<h1>Search for posts</h1>
<form method="get">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% endif %}
{% endblock %}
Thanks for reading.
Wrap the <input> in a form tag with the correct action, and make sure the form field has a correct name ("query" in your case), á la
<form method="get" action="{% url "blog:search" %}">
<input name="query" class="form-control" type="text" placeholder="Search" aria-label="Search">
</form>
You do need that template to show the results, don't get rid of it.

django-MPTT drilldown template

I am having some trouble getting a drilldown for mptt in my template.
I have the following model.
models.py
class Dimension_value(MPTTModel):
name = models.CharField(max_length = 200, null=True, blank = True, default = '')
parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return self.name
views.py
def show_dimensions(request):
return render(request, "accounts/dimension_detail.html", {'dimensions': Dimension_value.objects.all()})
template.py
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% drilldown_tree_for_node dimensions as drilldown cumulative count accounts.Dimension_value.name in game_count %}
{% for node,structure in drilldown|tree_info %}
{% if structure.new_level %}<ul><li>{% else %}</li><li>{% endif %}
{% if node == dimension %}
<strong>{{ node.name }}</strong>
{% else %}
{{ node.name }}
{% if node.parent_id == dimension.pk %}({{ node.game_count }}){% endif %}
{% endif %}
{% for level in structure.closed_levels %}</li></ul>{% endfor %}
{% endfor %}
</div>
</div>
<br>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}
I have added the view according to the documentation found here: https://django-mptt.readthedocs.io/en/latest/templates.html?highlight=examples#examples
However I get the following error.
Exception Type: AttributeError
Exception Value:
'TreeQuerySet' object has no attribute '_tree_manager'
Hope someone can nudge me in the right direction. Thanks!
You can do this by using some css and jquery
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% recursetree dimensions %}
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{node.level}}" aria-expanded="false" aria-controls="collapsed">
{{ node.name }}</a>
{% if not node.is_leaf_node %}
<ul class="children">
<div id="collapse{{node.level}}" class="children panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
{{ children }} </div>
</div>
</ul>
{% endif %}
{% endrecursetree %}
</div>
</div>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}

Can't display database data in Django

I am working on library website in which I want to display data from database which is Book name and description. But I'm not able to do that. Here is my code
views.py
from django.shortcuts import render
from .models import *
def index(request):
book_list = Book.objects.all()
return render(request,template_name='index.html', context={'book_list':book_list})
index.html
{% extends "base_generic.html" %}
{% block new_books %}
{% for b in book_list %}
<div class="card">
<img class="card-img-top" src=".." alt="Image">
<div class="card-body">
<h5 class="card-title">{{ book_list }} </h5>
<p class="card-text">Hello this is card text</p>
<a class="btn btn-primary">View this book</a>
</div>
</div>
{% endfor %}
{% endblock %}
You should work with b variable instead of book_list inside of for loop.
If your Book model contains title field, your code might look like this:
{% extends "base_generic.html" %}
{% block new_books %}
{% for b in book_list %}
<div class="card">
<img class="card-img-top" src=".." alt="Image">
<div class="card-body">
<h5 class="card-title">{{ b.title }} </h5>
<p class="card-text">Hello this is card text</p>
<a class="btn btn-primary">View this book</a>
</div>
</div>
{% endfor %}
{% endblock %}

Django NoReverseMatch while return render()

I always receive a NoReverseMatch error, and I don't know why.
This is the error message:
NoReverseMatch at /suche/any-thing/
Reverse for 'article_search' with arguments '(u'any thing',)' not found. 1 pattern(s) tried: ['suche/(?P[-\w]+)/$']
So as you can see, I'm entering a url with "-" instead of whitespace, but Django is looking for url pattern with the space instead of "-".
This is my url pattern:
url(r'suche/(?P<search>[-\w]+)/$', views.article_search_view, name='article_search'),
Surprisingly Django starts to compute my article_search_view, which looks like this:
def article_search_view(request, search=None):
"""Filters all articles depending on the search and renders them"""
articles = get_active_not_rented_articles()
search = re.sub(r"[-]", ' ', search)
articles = articles.filter(title__icontains=search)
articles = aply_sort(request, articles)
orderd_by = articles[0].get('filter')
articles = articles[1]
return render(request, 'article/list.html', {'object_list':articles, 'url_origin':'article_search', 'parameter':search,
'orderd_by':orderd_by})
As I checked with "print()" statements, the error is raised when the return render(...) statement is called.
If I do a return redirect(...) instead, no error will be raised.
For completeness, my article/list.html template:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div id =articles>
<div class="info_filter">
<div class="header_info_filter">
{% if orderd_by == "not" %}
<h1>Neueste Artikel</h1>
{% endif %}
{% if orderd_by == "distance" %}
<h1>Artikel in Ihrer Nähe</h1>
{% endif %}
{% if orderd_by == "price_asc" %}
<h1>Günstigste Artikel zuerst</h1>
{% endif %}
{% if orderd_by == "price_des" %}
<h1>Teuerste Artikel zuerst</h1>
{% endif %}
</div>
<div class="selection">
{% if parameter1 %}
<form action="{% url url_origin parameter1 parameter2 %}" method="post" accept-charset="utf-8">
{% else %}
{% if parameter %}
<form action="{% url url_origin parameter %}" method="post" accept-charset="utf-8">
{% else %}
<form action="{% url url_origin %}" method="post" accept-charset="utf-8">
{% endif %}
{% endif %}
{% csrf_token %}
<div class="select_filter">
<select name="filter" id="filter" >
<option value="distance">Entfernung</option>
<option value="price_asc">Preis, aufsteigend</option>
<option value="price_des">Preis, absteigend</option>
</select>
<div class="search_filter_btn">
<button type="submit" name="button">Sortieren</button>
</div>
</div>
</form>
</div>
{% if parent_categorys %}
<div class="category-path">
Ergebnisse für:
{% for category in parent_categorys %}
> {{ category.name }}
{% endfor %}
{% if parameter2 %}
: {{ parameter2}}
{% endif %}
</div>
{% else %}
Ergebnisse für: {{ parameter}}
{% endif %}
</div>
<div id="main" class="article_list">
{% for article in object_list %}
<div class="item">
<div class="list_img">
<a href="{{ article.get_absolute_url }}">
<img src="{% if article.main_picture %}{{ article.main_picture.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
</a>
</div>
<div class= "articles_fee" >
{{ article.fee }} €
</div>
{{ article.title }}
</div>
{% endfor %}
</div>
</div>
{% endblock %}
Let me know if you need more information.
In your view, you change search and replace hyphens with spaces. This causes an error when you use the url tag in your template, because the URL pattern does not allow spaces.
{% url url_origin parameter %}
You could fix the problem by adding the original search slug to the template context:
def article_search_view(request, search=None):
"""Filters all articles depending on the search and renders them"""
search_slug = search
articles = get_active_not_rented_articles()
search = re.sub(r"[-]", ' ', search)
...
return render(request, 'article/list.html', {'object_list':articles, 'url_origin':'article_search', 'parameter':search, 'search_slug': search_slug, 'orderd_by':orderd_by})
Then change the url tag:
{% url url_origin search_slug %}

Categories

Resources