Here, In this project I'm building a Ecommerce website and I'm using Django. So, here I want to show that if there is no product of category Electric, "Sorry, No Product is Available Right Now !!!" will be shown. where n is the number of product which is sent to this template from app views.
But I'm not getting "Sorry, No Product is Available Right Now !!!" as I've no product of Electric category in my database. How to fix this? where I'm doing wrong?
views.py
def electric(request):
product = Product.objects.all()
n = len(product)
params = {'product': product, 'range':range(1,n), 'n':n}
return render(request,'electric.html',params)
electric.html
{% if n is 0 %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>
{% else %}
<div class="album py-2 bg-gradient">
<div class="container">
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
{% for i in product %}
{% if i.category == "Electric" %}
<div class="col">
<div class="card shadow-sm">
<img src="{{i.image}}" />
<div class="card-body">
<h4 class="card-title">{{ i.product_name}}</h4>
<h6 class="card-subtitle mb-2 text-muted">
Category: {{i.category}}
</h6>
<p class="card-text">{{i.description}}</p>
<div class="buy d-flex justify-content-between align-items-center">
<div class="price text-success">
<h5 class="mt-4">Price: {{i.price}} BDT</h5>
</div>
<i class="fas fa-shopping-cart"></i> Add to Cart
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
views.py
def electric(request):
product = Product.objects.all()
return render(request,'electric.html',{'product': product})
electric.html
{% if product.count > 0 %}
-- your code --
{% else %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>
{% endif %}
Update your code as above. It will work.
Related
enter code heremodels
class Transactions(models.Model):
user=models.ForeignKey(CustomUser,related_name='accounts',on_delete=models.CASCADE, blank=True) recipient_account_type = models.CharField(max_length=230) recipient_name = models.CharField(max_length=100) recipient_acount_number = models.PositiveIntegerField() recipient_routing_number = models.PositiveIntegerField() recipient_bank_name = models.CharField(max_length=200) recipient_swift_code = models.CharField(max_length=100) recipient_sending_amount = models.DecimalField(max_digits=15, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) transaction_ID =models.IntegerField(default=ID) description = models.CharField(max_length=1000)
forms
class TransactionForm(forms.ModelForm):
class Meta:
model = Transactions
fields = ['recipient_account_type','recipient_name','recipient_acount_number',
'recipient_routing_number','recipient_bank_name','recipient_swift_code','recipient_sending_amount','description',]
Widget = forms.TextInput(attrs={'autofocus':'autofocus','size':'40', 'font-size':'xx-large'})
views
#login_required(login_url='/login/')
def send(request):
posts =Transactions.objects.filter(user=request.user)
form = TransactionForm()
if request.method=="POST":
form = TransactionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/success/')
else:
print(form.errors)
# messages.error(request, 'Failed, Resend')
context = {'form':form,'posts':posts}
return render(request, 'index_user/send-money.html', context)
**template**
{% extends 'about/user-base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% load humanize %}
{% block content %}
<!-- Content
============================================= -->
<div id="content" class="py-4">
<div class="container">
<div class="row mt-4 mb-5">
<div class="col-lg-11 mx-auto">
<div class="row widget-steps">
<div class="col-12 step active">
<div class="step-name">Details</div>
</div>
</div>
</div>
</div>
<h2 class="fw-400 text-center mt-3">Send Money</h2>
<p class="lead text-center mb-4">Send your money at anytime, anywhere in the world.</p>
<div class="row">
<div class="col-md-18 col-lg-7 col-xl-6 mx-auto bg-primary">
<div class="bg-white shadow-sm rounded p-3 pt-sm-4 pb-sm-5 px-sm-5 mb-4">
<hr class="mx-n3 mx-sm-n5 mb-4">
<div class="bg-white shadow-sm rounded p- pt-sm-5 pb-sm-5 px-sm-5 mb-4 bg-secondary">
<div class="text-center bg-primary p-4 rounded mb-4">
<h3 class="text-10 text-white fw-400">${{user.account_balance|intcomma}}</h3>
<p class="text-white">Available Balance</p>
{% comment %} Withdraw Full Amount </div> {% endcomment %}
<!-- Send Money Form
============================ -->
<p style="color: red; font-size:large">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</p>
<center style="background-color: #007bff;">
<form id="form-send-money" method="POST" action="" class="bg-success" >
{% csrf_token %}
<div class="mb-3 pb-sm-5 px-sm-5">
{% comment %} <label for="withdrawto" class="form-label">Withdraw From</label> {% endcomment %}
<br>
{% comment %} <select id="withdrawto" class="form-select px-sm-4 pb-sm-1" name="">
<option value="">FNMB Bank - {{user.account_number}}</option>
</select> {% endcomment %}
</div>
<div id="id_long_desk" class="mb-3 px-sm-4 pb-sm-9">
<label for="emailID" class="form-label">Recipient Full Name</label>
<br>
{{form.recipient_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Number</label>
<br>
{{form.recipient_acount_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Bank Name</label>
<br>
{{form.recipient_bank_name}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Routing Number</label>
<br>
{{form.recipient_routing_number}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Swift Code</label>
<br>
{{form.recipient_swift_code}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Account Type</label>
<br>
{{form.recipient_account_type}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Recipient Sending Amount</label>
<br>
{{form.recipient_sending_amount}}
</div>
<div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Description</label>
<br>
{{form.description}}
</div>
{% comment %} <div class="mb-3 px-sm-4 pb-sm-1">
<label for="emailID" class="form-label">Fees</label>
<br>
$ {{form.fees}}
</div> {% endcomment %}
<!-- <p>Transfer Fees <span class="float-end"> 12.21 USD</span></p> -->
<hr>
<div class="d-grid"><button class="submit btn btn bg-white">Send</button></div>
<hr>
</form>
</center>
<!-- Send Money Form end -->
</div>
</div>
</div>
</div>
</div>
<!-- Content end -->
{% endblock %}
Have you checked whether your form is valid with something like the following?
if form.is_valid():
obj = form.save()
else:
# errror handling? debug with form.errors...
If your code does look like above, please add more info (like the form handling method as a whole)
My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed.
I think data are not passing from view.py to html template.How i can fix this?
the code is given below.
views.py
def collectionsview(request, slug):
if(Category.objects.filter(slug=slug, status=0)):
products=Product.objects.filter(category__slug=slug)
category_name=Category.objects.filter(slug=slug).first()
contex={products:"products",category_name:"category_name"}
print(products)
return render(request, "store/product/index.html", contex)
else:
return HttpResponse('This is not a valid product')
html template
{% extends 'store/layouts/main.html' %}
{% block title %}Home{% endblock title %}
{% block body %}
<div class="container mt-3">
<div class="row">
<div class="col-md-12">
<h4>{{category_name}}</h4>
<div class="row">
{% for item in products %}
<div class="col-md-2">
<div class="card">
<a href="#">
<div class="card-body ">
<div class="card-image">
<img src="{{item.imge.url}}" alt="" width="100%" height="100%">
<h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4>
</div>
<span>{{item.original_price}}</span>
<span>{{item.selling_price}}</span>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock body %}
I am building a web app using django and I get an error, I couldn't figure out what is the problem behind it.
I have three models( Category, SubCategory, Article) in my url I want something like that (localhost:8000/categories/Id_category/Id_subcategory)
the url (localhost:8000/categories/Id_category) worked perfectly but (localhost:8000/categories/Id_category/Id_subcategory) didn't work I get this error enter image description here
So here is my code that I tried to make it:
#views.py
def categorie(request):
Catégorie_list=Catégorie.objects.all()
context = {
'Catégorie_list':Catégorie_list,
}
return render(request,'articles/Category.html',context)
def souscategorie(request,categoryID):
SousCatégorie_list=SousCatégorie.objects.order_by('désignation').filter(Catégorie_identifiant_id=categoryID)
name_category=Catégorie.objects.get(id=categoryID)
articles=Article.objects.select_related('Sous_Catégorie__Catégorie_identifiant').filter(Sous_Catégorie__Catégorie_identifiant_id=categoryID)
context = {
'SousCatégorie_list':SousCatégorie_list,
'name_category': name_category,
'articles':articles
}
return render(request,'articles/SubCategory.html',context)
def articl(request,categoryID,articleID):
return render(request,'articles/article.html')
#articles/urls.py
urlpatterns=[
path('',views.categorie, name='Category'),
path('<int:categoryID>/',views.souscategorie, name='SubCategory'),
path('<int:categoryID>/<int:articleID>/',views.articl, name='article'),
path('search',views.search, name='search'),
]
#my template Category.html
{% if Catégorie_list %}
{% for category in Catégorie_list %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<a href="{% url 'SubCategory' category.id %}">
<img class="card-img-top" src="{{ category.photo_main.url }}" alt="{{ category.désignation }}"> </a>
<div class="card-body">
<div class="listing-heading text-center">
<a href="{% url 'SubCategory' category.id %}" style="text-decoration: none;">
<h4 class="text-primary" >{{ category.désignation }}</h4>
</a>
</div>
<hr>
<div class="listing-heading text-center">
<a class="text-primary" >{{ category.Description }}</a>
</div>
<hr>
Voir la catégorie
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>Aucune catégorie disponible</p>
</div>
{% endif %}
#my template Subcategory.html
<div class="row">
{% if articles %}
{% for article in articles %}
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="{{ article.photo_main.url }}" alt="">
<div class="card-body">
<h4 class="card-title">
{{ article.désignation }}
</h4>
<h5>{{ article.Sous_Catégorie }}</h5>
<p class="card-text">{{ article.Description }}</p>
</div>
<div class="card-footer">
<h6 class="text-muted">Ajouter au panier</h6>
</div>
</div>
</div>
{% endfor %}
{% else %}
<a class="list-group-item"> Aucune sous catégorie disponible</a>
{% endif %}
</div>
I'm building a blog using Django and I just integrated markdown. How do I make sure that the truncated part of the body of a post (which is telling a little of what you'll see when that particular post is opened) doesn't display markdown?
I created a template filter markdown:
from django.utils.safestring import mark_safe
from django import template
import markdown
register = template.Library()
#register.filter(name='markdown')
def markdown_format(text):
return mark_safe(markdown.markdown(text))
Here's the usage in the post_list.html template
{% extends "base.html" %}
{% load blog_tags static disqus_tags %}
{% disqus_dev %}
{% block content %}
<div class="jumbotron">
<h1 class="heading-font">Shelter At Your Crossroads</h1>
<p class="lead">...some random ass text that could serve as motto or something</p>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8">
{% if tag %}
<h2 class="mb-4">Posts tagged with "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<div class="card mb-5">
<img class="card-img-top img-fluid" src="{{ post.image.url }}" alt="{{ post.title }}">
<div class="card-body">
<h2 class="card-title">{{ post.title }}</h2>
<p class="card-text">{{ post.body|markdown|truncatewords_html:50 }}</p>
<i class="fa fa-book" aria-hidden="true"></i> Read More
<i class="fa fa-share-alt" aria-hidden="true"></i> Share Post
<div class="float-right">
<i class="fa fa-tags"></i>
{% for tag in post.tags.all %}
<a href="{% url 'post_list_by_tag' tag.slug %}">
<span class="badge badge-pill badge-info">{{ tag.name }}</span>
</a>
{% endfor %}
</div>
</div>
<div class="card-footer text-center text-muted">
Posted on {{ post.publish.date }} by {{ post.author.get_full_name }}
</div>
</div>
{% endfor %}
</div>
<div class="col-lg-4">
<div class="card border-dark mb-3">
<div class="card-header">Post Count</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Total Number of Posts</h4>
<p class="card-text text-center display-3">{% total_posts %}</p>
</div>
</div>
<div class="card border-dark mb-3">
<div class="card-header">Latest Posts</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Most Recent Posts</h4>
<p class="card-text">{% show_latest_posts 3 %}</p>
</div>
</div>
<div class="card border-dark mb-3">
<div class="card-header">Latest Comments</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Most Recent Comments</h4>
<p class="card-text">{% disqus_recent_comments shortname 5 50 1 %}</p>
</div>
</div>
</div>
</div>
{% include 'includes/pagination.html' with page=posts %}
</div>
{% endblock %}
The filter was used on line 22 - {{ post.body|markdown|truncatewords_html:50 }}
How do I make display just normal text?
I wanted to use class based views and went through the django documentation and I get noerror messages but wind up with an empty template. I had it working with the non-classed based views. How do I reformat the code so that it renders the template? The template consists of a title, some headings, a navigational menu, flags for selecting instructions in different languages,
followed by a form which shows a flag, policy name char field, and a check box control. I think the initial = {'key': 'value'} in the view forms incorrect but I don't know what to replace it with. Thanks in advance.
forms.py
from django import forms
from policytracker.models import Flag, Label_Links
class PolicyStartForm( forms.Form ):
flags = Flag.objects.all()
policy = Label_Links.objects.all().filter(iso_language='en')[0]
frm_policy1_name=[]
for flag in flags:
frm_policy1_name.append(forms.CharField(max_length=40))
policy_dict = { 'new_policy_link' :policy.nav_section_new_policy_link,
'new_policy_label' :policy.nav_section_new_policy_label,
'graphs_link':policy.nav_section_graphs_link,
'graphs_label' :policy.nav_section_graphs_label,
'account_link' :policy.nav_section_account_link,
'account_label' :policy.nav_section_account_label,
'policy_list_link':policy.nav_section_list_policies_link,
'policy_list_label':policy.nav_section_list_policies_label,
'login_link' :policy.nav_section_login_link,
'login_label' :policy.nav_section_login_label,
'new_policy1_heading' :policy.new_policy1_heading,
'new_policy1_title_label':policy.new_policy1_title_label,
'policy_needs_translation_label':policy.new_policy1_needs_trans_label,
'policy1_submit_label': policy.new_policy1_submit_button_label,
'policy1_tip_msg' :policy.new_policy1_tip_msg,
't_logged_in' :True,
'frm_policy_name' :frm_policy1_name,
't_flags' :flags }
</code>
<code>
views.py
# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponseRedirect
from policytracker.forms import LoginForm, PolicyStartForm
from policytracker.models import Flag, Label_Links
from django.views import View
class PolicyStartView(View):
template_name = 'policystart.html'
initial = {'key': 'value'}
form_class = PolicyStartForm
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
</code>
<code>
policystart.html
{% extends "policy-base.html" %}
{% block navsection %}
<div class="container top">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h1 class="text-center">{{ new_policy1_heading }}</h1>
</div>
</div>
{% if t_policy_details %}
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-left" id="week_start">2017-02-11</h4></div>
<div class="col-md-4 col-xs-4">
<h4 class="text-center" id="week_number">Week 1</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-right" id="week_end">2016-09-18</h4></div>
</div>
{% endif %}
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand hidden navbar-link" href="#"> Policies</a>
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
</div>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden" role="presentation">{{ new_policy_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ graphs_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ account_label }}</li>
<li role="presentation">{{ policy_list_label }}</li>
{% if not t_logged_in %} <li role="presentation">{{ login_label }}</li> {% endif %}
</ul>
</div>
</div>
</nav>
</div>
</div>
{% include "pol-new1-lang.html" %}
</div>
<div class="container middle-container">
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-8">
<h4>{{ new_policy1_title_label }}</h4>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<h4 class="text-center">{{ policy_needs_translation_label }}</h4>
</div>
</div>
<form method="POST">
{% csrf_token %}
{% load static %}
{% for f in t_flags %}
<div class="row flag">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-2"><img src="{% static f.flag_image_filename %}"></div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-9">
<input class="form-control" type="text" name="policytitle">
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<input class="form-control" type="checkbox" name="needstranslation">
</div>
</div>
{% endfor %}
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<button class="btn btn-default" type="submit">{{ policy1_submit_label }}</button>
</div>
</div>
</form>
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<p>{{ policy1_tip_msg }}</p>
</div>
</div>
</div>
{% endblock %}
</code>
You're using a load of variables in your template, but you aren't actually sending any of them to the context; the only thing your view passes is form. If you want to use things like new_policy1_heading, policy_needs_translation_label and t_flags you need to define them in your view and send them to the template from there.
Actually, it looks like you've completely misunderstood the jobs of forms and views. All the code you've currently put inside your form actually belongs in the view, and you should use policy_dict as the template context. It doesn't look like you need a form class at all.
Even there, though, you're doing much more work than you need to. There's no need to send all the specific fields of the policy object individually; just send policy and then in the template you can do {{ policy.policy_needs_translation_label }} etc.