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>
Related
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'),
...
}
My main page on my website shows all the possible listings and when one of them is clicked on, the user is meant to be taken to a page that shows the listing's information. (This page is not finished yet.) This means that I need to be able to know which listing has been clicked on so I need a way to get the id of the listing.
I've tried to do this by taking in a id parameter/argument that should be used inside the function to find out which listing this is.
I want the url to be http://127.0.0.1:8000/[id]/[name of listing] where [id] and [name of lsiting] and the actual ids and names of the listings. id should be a number and name_of_listing should be a string. (The id is in Listing.id and the name of the listing is in Listing.name - Listing is the name of the model and the id and name are fields.)
How do I get the id of a listing through a link?
index.html: (this just displays all the listings - I've used comments to show where the links are)
<main>
<div class="listings-container">
{% for i in listings %}
<div class="listing">
{% if i.photo_present != None %}
<div class="img-container">
{% if i.photo_url != None %}
<div class="img-center">
<a href="{% url 'listing' i.id %}"> <!-- this is where the link is -->
<img src=" {{ i.photo_url }} " alt="">
</a>
</div>
{% else %}
<div class="img-center">
<a href="{% url 'listing' i.id %}"> <!-- this is where the link is -->
<img src=" media/{{ i.photo_upload }} " alt="">
</a>
</div>
{% endif %}
{% else %}
<div class="img-center">
<img src="media/images/no-image.jpg" alt="No Image">
</div>
</div>
{% endif %}
<div class="listing-separation"></div>
<div class="info-container">
<div class="top-info">
<div class="listing-title">
<a href="{% url 'listing' %}"> <!-- this is where the link is -->
<h4>{{ i.name }}</h4>
</a>
</div>
<div class="listing-price">
<a href="{% url 'listing' %}"> <!-- this is where the link is -->
<strong>£{{ i.highest_bid }}</strong>
</a>
</div>
</div>
<div class="listing-description">
<a href="{% url 'listing' %}"> <!-- this is where the link is -->
<p>{{ i.description }}</p>
</a>
</div>
</div>
</div>
<hr>
{% endfor %}
</div>
</main>
views.py: (attempt to get the listing id)
from .models import Listing # this is the name of the model
def listing(request, id):
listing = Listing.objects.get(pk=id)
return render(request, 'auctions/listing.html', {
'listings': Listing.objects.all(),
'listing': listing
})
urls.py:
path('<int:id>/<str:name>', views.listing, name='listing')
listing.html: (what should be shown when the user clicks on the link)
{% extends "auctions/layout.html" %}
{% block body %}
<h1>
{{ listing.id }}
</h1>
{% endblock %}
To get the id use the 'pk' attribute, remember that in the url you also requested the name of the list
{% url 'listing' i.pk i.name %}
Also correct the url by inserting a / at the end
path('<int:id>/<str:name>/', views.listing, name='listing')
In other parts of the code you used the following link
{% url 'listing' %}
Would this link be the same as the previous one or a separate page? if it is another page you must implement a new url without parameters
I have implemented search bar functionality with autocomplete feature. All is good except the fact that in HTML serach results contain multiple the same object. For instance, when I put 2 in my searchbar I see 4 the same in my HTML file. What I want is to get unique objects.
views.py
#login_required
def search_address_qa(request):
query = request.GET.get('title')
payload = []
if query:
lookups = Q(title__icontains=query)
address_objects = Article.objects.filter(lookups)
address_objects_qa = QA.objects.filter(lookups)
for address_object in address_objects or address_objects_qa:
payload.append(address_object.title)
return JsonResponse({'status':200, 'data': payload})
#login_required
def search_articles(request):
query = request.GET.get('q')
article = Article.objects.filter(title__icontains=query)
qa_list = QA.objects.filter(title__icontains=query)
if query is not None:
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
article = Article.objects.filter(lookups)
qa_list = QA.objects.filter(lookups)
context = {
'search_articles': article,
'query_name': query,
'qa_list': qa_list
}
return render(request, 'search/search_articles.html', context)
search_view.html
{% extends 'base.html' %}
<title>{% block title %}search results{% endblock %}</title>
{% block search %}
{% include 'main/sidebar.html'%}
<link rel="stylesheet" type="text/css" href="/static/search.css">
<div class="d-flex justify-content-end h-100 pb-4">
<div>
{% if user.is_authenticated %}
<form action="{% url 'search_articles' %}" method="get" id="search">
{% csrf_token %}
<div class="searchbar " id="autocomplete">
<input name="q" type="text" placeholder="Search articles" class="search_input">
<i class="fas fa-search"></i>
<ul class="autocomplete-result-list"></ul>
</div>
</form>
{% endif %}</div>
</div>
{% endblock search %}
{% block content %}
<div class="d-flex justify-content-start pb-4">Search results for my question: <div class="ml-1 fw-bold"> {{ query_name }} </div></div>
<div class="container-fluid pb-4">
<h4>Articles</h4>
<hr>
<div class="row row-flex row-cols-1 row-cols-md-3 g-4">
{% for article in search_articles %}
<div class="col-lg-3 d-flex align-items-stretch">
<a href="{{ article.get_absolute_url }}">
<div class="card h-100 shadow text-left">
<h5 class="card-header">{{article.title}}</h5>
<img src="/static/preview_homepage3.png" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ article.slug }}</h5>
<p class="card-text">
{% comment %} {% lorem 10 w %} {% endcomment %}
{{article.body | safe | truncatechars:75}}
</p>
</a><br>
{% include 'main/tag_cards.html' %}
</div>
<div class="card-footer">
<small class="text-muted">{{ article.publish|date:"d F Y" }}</small>
</div>
</div>
</div>
{% empty %}
<div class="container d-flex justify-content-center">No results</div>
{% endfor %}
</div>
</div>
<h4>Related questions</h4>
<hr>
<div class="container h-100 py-2 mb-4">
{% for qa in qa_list %}
<div class="card text-dark bg-light mb-3 text-left">
<a href="{{ qa.get_absolute_url }}">
<h5 class="card-header">Q: {{qa.title}}</h5>
<div class="card-body">
<div class="card-title text-justify">A: {{ qa.answer |safe | striptags }}</div>
{% comment %} <p class="card-text"> {{ qa.author }}</p> {% endcomment %}
</div>
<div class="card-footer">
<small class="text-muted">Published: {{qa.publish}}</small>
</div>
</a>
</div>
{% empty %}
<p>No results</p>
{% endfor %}
{% endblock %}
You can make use of Django's distinct() QuerySet method
.disctinct() Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.
Change
article = Article.objects.filter(lookups)
to
article = Article.objects.filter(lookups).distinct()
Why does it happen?
In your case, this happens because you are using the Q object,
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
suppose your search text is "test" and you have a row in the table with title="text" and tag_name="text", then the lookup will match both title and tag which leads to generating duplicate rows (since you are performing an OR operation in your lookkups) with the same result.
I'm trying to write a small online store on Django and I have a small problem:
I want to display the listveiw immediately after the page loads, but Django does not allow it
I tried to make a display by pressing a button, and it worked, but I would like to make a display as soon as the page loads
urlpatterns = [
path('', views.index, name = 'INDEX'),
path ('prod/', ListView.as_view(queryset=Product.objects.all(), template_name="mainPage/homePage.html"))
]
Can you help me?
my homePage.html:
{% extends "mainPage/wrapper.html" %}
{% load static %}
{% block content %}
<div class="container" style="margin-top: 5%">
{% for val in object_list %}
<div class="card" style="width: 18rem;">
<img src="{{ val.Image_path }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ val.Name }}</h5>
{{ val.Category }}
<p class="card-text">{{ val.Description }}</p>
Buy
</div>
</div>
{% endfor %}
</div>
{% endblock %}`
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 %}