I am creating a printing ordering service website in Django and I am stuck on the order page.
I have three tables named "product" ,"size", and "sizeProductMap" table.
views.py
products = Product.objects.get(prod_ID=id)
print(products.prod_Name)
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = []
for data in sizesmap:
sizes = data.size_id
sizeslist.append(sizes.prod_size) # Here I am getting all the sizes I needed.
print(sizes.prod_size)
return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist})
product.html
{% extends 'GalaxyOffset\basic.html' %}
{% block title%}Products{% endblock %}
{% block body%}
<div class="card my-2 mx-0 auto">
<div class="mx-4 my-2">
<h1>{{ products.prod_Name }}</h1>
</div>
<div class="row">
<div class="col-3">
<img class="border border-secondary my-4 mx-4" height="200"
src="{{products.prod_img.url}}"
width="200"/>
</div>
<div class="col-8 my-4">
<p> {{products.prod_Desc}}</p>
</div>
<div class="dropdown-divider"></div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="card mx-2 my-2 border border-secondary">
<div class="mx-2 mt-4">
{% for category in categories %}
<a id="{{ category.prod_ID }}" class="dropdown-item" href="{% url 'product' category.prod_ID%}">
{{ category.prod_ID }}. {{ category.prod_Name }}</a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<div class="card mx-2 my-2">
<div class="my-2">
<!-- How can I reduce Number of Line of code here. -->
{% for s in sizeslist %}
<input type="radio" name="sizes">{{s}}
</br>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
Can you help me here to reduce the Numer of Lines in my views.py for fetching sizes and displaying in product.html?
You can use a list comprehension here.
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = [data.size_id.prod_size for data in sizesmap]
or use .values()
Ex:
sizeslist = SizeProductMapping.objects.filter(prod_id=id).values('size_id__prod_size')
Related
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.
Currently trying to iterate over a list using Django templating.
What I am trying to achieve is having multiple row with three columns. The current logic creates a one row with around every third card element.
What would be the best approach for creating each row w/ three columns?
{% extends "stockwatcher/base.html" %}
{% block content %}
<div class="container">
{% for stock in stocks %}
{% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %}
<div class="row">
{% endif %}
<div class="col-sm">
<div class="card text-white bg-info mb-3" style="max-width: 18rem;">
<div class="card-header">{{stock.transaction_date}}</div>
<div class="card-body">
<h5 class="card-title">{{ stock.id }} {{stock.ticker}} </h5>
<p class="card-text">{{stock.senator}} - {{stock.type}}</p>
</div>
</div>
</div>
{% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %}
</div>
{% endif %}
{% endfor %}
</div>
{% endblock content %}
You should use row div outside the for loop and bootstrap classes will handle the rest for you. You can also use {% empty %} tag to handle empty list.
{% extends "stockwatcher/base.html" %}
{% block content %}
<div class="container">
<div class="row">
{% for stock in stocks %}
<div class="col-sm">
<div class="card text-white bg-info mb-3" style="max-width: 18rem;">
<div class="card-header">{{stock.transaction_date}}</div>
<div class="card-body">
<h5 class="card-title">{{ stock.id }} {{stock.ticker}} </h5>
<p class="card-text">{{stock.senator}} - {{stock.type}}</p>
</div>
</div>
</div>
{% empty %}
No items
{% endfor %}
</div>
</div>
{% endblock content %}
I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
model = HotelBookingAd
form_class = HotelBookingAdForm
template_name = "account/article-create-update.html"
def form_valid(self,form):
form.save()
return super(HotelAdCreate).form_valid(form)
Forms.py
class HotelBookingAdForm(forms.ModelForm):
class Meta:
model = HotelBookingAd
fields = '__all__'
def clean_sales_price(self):
sales_price = self.cleaned_data["sales_price"]
purchase_price = self.cleaned_data["purchase_price"]
if sales_price > purchase_price:
raise forms.ValidationError("error.")
print("error")
return sales_price
Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title- mb-0">ایجاد آگهی </h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div class="col-6">
{{form.title|as_crispy_field}}
</div>
<div class="col-6">
{{form.hotel_name|as_crispy_field}}
</div>
<div class="col-12">
{{form.sale_reason|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_in_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_out_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.purchase_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.sales_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.city_name|as_crispy_field}}
</div>
<div class="col-6">
{{form.room_type|as_crispy_field}}
</div>
<div class="col-6">
{{form.confirm|as_crispy_field}}
</div>
{% if user.is_superuser %}
<div class="col-6">
{{form.slug_generator|as_crispy_field}}
</div>
{% endif %}
</div>
<button class="btn btn-success">ارسال مقاله</button>
{% if user.is_superuser and request.resolver_match.kwargs.pk %}
<a class="btn btn-danger "href="{% url 'account:hotelad-delete' request.resolver_match.kwargs.pk %}">
حذف مقاله
</a>
<a target="_blank" class="btn btn-dark "href="{% url 'primary:preview' request.resolver_match.kwargs.pk %}">
پیش نمایش
</a>
{% endif %}
</form>
</div>
</div>
</div>
{% endblock %}
I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)
I made my macbook disk format.
After the format, I included my project.
However, photos are not displayed on the project page.
If I go to a specific product, (single page) this is a photo.
The logo is also visible.
Pictures are not displayed to me only collectively.
Safari didn't see 'css/mdb.min.css'
Maybe I don't have something installed?
Before, everything worked.
Here photo display
product.html
{% extends 'base.html' %}
{% load static %}
{% block title %} {{ product.name }} - PVB {% endblock %}
{% block content %}
<main class="mt-5 pt-4">
<div class="container dark-grey-text mt-5">
<!--Grid row-->
<div class="row wow fadeIn">
<!--Grid column-->
<div class="col-md-6 mb-4">
<img src="{{ product.photo.url }}" class="img-fluid" alt="">
</div>
<!--Grid column-->
<div class="col-md-6 mb-4">
<!--Content-->
<div class="p-4">
<div>
<h2>{{product.product_name}}</h2><hr>
<h5><p>Description</p></h5>
<p class="text-justify"><h6>{{product.description}}</h6></p>
<p class="text-justify"><h6>Weight: {{product.weight}}g</h6></p><hr>
</div>
</div>
</div>
</div>
<hr>
</div>
</main>
{% endblock %}
here no
products.html
{% extends 'base.html' %}
{% load static %}
{% block title %} Offer - PVB {% endblock %}
{% block content %}
<section id="marks">
<div class="container">
<header>
<h1>Our Offer</h1>
</header>
</div>
</section>
<!-- Offers -->
<section class="text-center mb-4 py-4">
<div class="container">
<div class="row">
{% if products %}
{% for product in products %}
<!--Grid column-->
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="{{ product.photo.url }}" class="card-img-top" alt="">
<a href="{% url 'product' product.id %}">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<h6 class="grey-text">{{ product.category }}</h6>
<h5>
<strong>
{{ product.product_name }}
</strong>
</h5>
</div>
</div>
</div>
<!--Grid column-->
{% endfor %}
{% else %}
<div class="col-sm-12 sm-12">
<p>No Products Available</p>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
Check your media folder , May be its empty
So I am developing a website and for the life of me I can't figure out how to align the description, price, stock and add cart button in multiple versions of the same <div>. I know it is to do with the size of the image I am using but I'm not sure how to fix this.
Here is a diagram of how I want it to look:
But when I apply a 'h-100' class to the card <div> this is what happens:
I want the images to keep their positions but for the descriptions, add cart button and price/stock to all be horizontally aligned, as well as the height of the overall cards to be the same.
Here is my Django template code:
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron">
<h2>Welcome to MyTea</h4>
<p>Here we have teas of all varieties from all around the globe</p>
</div>
<div class="row">
<div class="col-sm-3">
<h4>Categories</h4>
<ul class="list-group">
All Categories
{% for c in countcat %}
<a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}}
<span class="badge badge-light">{{c.num_products}}</span>
</a>
{% endfor %}
</ul>
</div>
<div class="col-sm-9">
{% for product in products %}
{% if forloop.first %}<div class="row">{% endif %}
<div class="col-sm-6">
<div class="card border-primary mt-3 h-100">
<div class="card-header"><h3>{{product.name}}</h3></div>
<div class="card-body">
{% if product.image %}
<div class="h">
<img src="{{product.image.url}}" class="img-fluid">
</div>
{% endif %}
<p class="bg-light font-weight-light ">{{product.description}}</p>
{% if product.stock > 0 %}
<a href="{% url 'add_cart' product.id %}" type="button" class="btn btn-primary btn-sm mb-2">
<p class="m-0">Add to cart</p>
</a>
{% else %}
<a href="#" type="button "class="btn btn-danger btn-sm mb-2">
<p class="m-0">Out of stock</p>
</a>
{% endif %}
<div class="card-footer">
<p>Price: €{{product.price}}</p>
<p>Stock left: {{product.stock}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
Thanks for any help
The code can be corrected with a simple re-alignment of the content inside .card and correctly closing </div> statements.
Remove {% if forloop.first %}<div class="row">{% endif %} statement and place <div class="row"> above the for loop.
Add to cart and Out of stock buttons should be placed inside .card-footer and .card-body should be closed appropriately. This will leave the image and description within .card-body
Make sure h-100 class is added to `.card'.
Might I suggest adding end of div comments to all the div statements. The code is readable better in this way and helps in mitigating missing or misplaced </div> statements.
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron">
<h2>Welcome to MyTea</h4>
<p>Here we have teas of all varieties from all around the globe</p>
</div>
<!-- .jumbotron -->
<div class="row">
<div class="col-sm-3">
<h4>Categories</h4>
<ul class="list-group">
All Categories
{% for c in countcat %}
<a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}}
<span class="badge badge-light">{{c.num_products}}</span>
</a>
{% endfor %}
</ul>
</div>
<!-- .col-sm-3 -->
<div class="col-sm-9">
<div class="row">
{% for product in products %}
<div class="col-sm-6">
<div class="card border-primary mt-3 h-100">
<div class="card-header">
<h3>{{product.name}}</h3>
</div>
<!-- .card-header -->
<div class="card-body">
{% if product.image %}
<div class="h">
<img src="{{product.image.url}}" class="img-fluid">
</div>
<!-- .h -->
{% endif %}
<p class="bg-light font-weight-light ">{{product.description}}</p>
</div>
<!-- .card-body -->
<div class="card-footer">
{% if product.stock > 0 %}
<a href="{% url 'add_cart' product.id %}" type="button" class="btn btn-primary btn-sm mb-2">
<p class="m-0">Add to cart</p>
</a>
{% else %}
<a href="#" type="button " class="btn btn-danger btn-sm mb-2">
<p class="m-0">Out of stock</p>
</a>
{% endif %}
<p>Price: €{{product.price}}</p>
<p>Stock left: {{product.stock}}</p>
</div>
<!-- .card-footer -->
</div>
<!-- .card -->
</div>
<!-- . col-sm-6 -->
{% endfor %}
</div>
<!-- .row -->
</div>
<!-- .col-sm-9 -->
</div>
<!-- .row -->
</div>
<!-- .container-fluid -->
{% endblock content %}