I have two models SubCategory and Product i created a listview with model set to SubCategory and reference its related product set in template but items are not being loaded don't know what I have missed
models
class SubCategory(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=300)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=120)
price = models.FloatField()
image = models.ImageField(upload_to='pdt_imgs/')
sku = models.IntegerField()
available = models.BooleanField(default=True)
discount = models.IntegerField(default = 0)
category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
def __str__(self):
return self.name
Template in which I tried to reference product items related to subcategories
<div class="ps-block__categories">
<h3>Clothing & <br> Apparel</h3>
<ul>
{% for subcategory in object_list %}
<li>{{ subcategory.name }}</li>
{% endfor %}
</ul><a class="ps-block__more-link" href="#">View All</a>
</div>
<div class="ps-block__slider">
<div class="ps-carousel--product-box owl-slider" data-owl-auto="true" data-owl-loop="true"
data-owl-speed="7000" data-owl-gap="0" data-owl-nav="true" data-owl-dots="true" data-owl-item="1"
data-owl-item-xs="1" data-owl-item-sm="1" data-owl-item-md="1" data-owl-item-lg="1" data-owl-duration="500"
data-owl-mousedrag="off"><img src="{% static 'img/slider/home-3/clothing-1.jpg' %}" alt=""><a href="#"><img
src="{% static 'img/slider/home-3/clothing-2.jpg' %}" alt=""></a><a href="#"><img
src="{% static 'img/slider/home-3/clothing-3.jpg' %}" alt=""></a></div>
</div>
<div class="ps-block__product-box">
{% for product in object.product_set.all %}
<div class="ps-product ps-product--simple">
<div class="ps-product__thumbnail"><a href="product-default.html"><img src="{{ product.image.url }}"
alt=""></a>
{% if product.discount > 0 %}
<div class="ps-product__badge">-{{ product.discount }}%</div>
{% endif %}
{% if product.available == False %}
<div class="ps-product__badge out-stock">Out Of Stock</div>
{% endif %}
<ul class="ps-product__actions">
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Read More"><i
class="icon-bag2"></i></a></li>
<li><a href="#" data-placement="top" title="Quick View" data-toggle="modal"
data-target="#product-quickview"><i class="icon-eye"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Add to Whishlist"><i
class="icon-heart"></i></a></li>
<li><a href="#" data-toggle="tooltip" data-placement="top" title="Compare"><i
class="icon-chart-bars"></i></a></li>
</ul>
</div>
<div class="ps-product__container">
<div class="ps-product__content" data-mh="clothing"><a class="ps-product__title"
href="product-default.html">{{ product.name }}</a>
<div class="ps-product__rating">
<select class="ps-rating" data-read-only="true">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="2">5</option>
</select><span>01</span>
</div>
<p class="ps-product__price sale">UGX{{ product.price }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
For now I cant load product items despite trying reference them as related objects of subcategory
Related
I have made a django e-comm website , when I press the add to cart button on my home page I have written a function which should change the status of a product from false to true once it is added in the cart but it does not work
I have given my cart.py and index.html code
Thank you
cart.py
from django import template
register = template.Library()
#register.filter(name='is_in_cart')
def is_in_cart(product,cart):
keys = cart.keys()
for id in keys:
print(id , product.id)
if int(id) == product.id:
return True
return False
index.html
{% extends 'main/base.html'%}
{% block title %}
index
{% endblock %}
{% block content %}
{% load cart %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class="list-group mt-3">
{% for items in category %}
{{items.Category_name}} <!--i first used a small c for category but it did not pick the words from my category.py fle-->
{% endfor %}
</div>
</div>
<div class="col-lg-9">
<div class="row">
{% for items in product %}
<div class="card mx-auto mb-3 mt-3" style="width: 18rem;">
<img class="card-img-top" src="{{items.product_image.url}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{items.product_name}}</h5>
<p class="card-text"><b>{{items.product_price}}</b></p>
<p class="card-text"><b>{{items.product_detail}}</b></p>
{{product | is_in_cart:request.session.cart }}
<form action="/" mthod="POST">
{% csrf_token %}
<input hidden type="text" name='product' value='{{items.id}}'>
<input href="#" type="submit" class="float-right btn btn-light border btn-sm" value="Add to Cart">
</form>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text.
I want to make it look something like this
This is my model
class Project(models.Model):
projectTemplate = CloudinaryField('image')
projectTitle = models.TextField(default="Title ")
desc = models.TextField(default="not mentioned")
projectLink = models.URLField(max_length=200, default="not mentioned")
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.projectTitle} - {self.desc[:15]} ..'
views.py
def projects(request):
Projects = Project.objects.all()
return render(request, 'devpage/projects.html',{'Projects': Projects})
This is my current DTL
{% for project in Projects %}
<div class="col">
<div class="card shadow-sm">
<img src="{{ project.projectTemplate.url }}" height="225" width="100%">
<div class="card-body">
<h6 class="text-center">
{{ project.projectTitle }}
</h6>
<p class="card-text">{{ project.desc }}</p>
<div class="mb-3">
<span class="badge rounded-pill bg-secondary">Django</span>
<span class="badge rounded-pill bg-success">Python</span>
</div>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a
href="{{ project.projectLink }}" target="_blank" type="button"
class="btn">View</a></button>
</div>
<small class="text-muted">{{ project.created_at }}</small>
</div>
</div>
</div>
</div>
{% endfor %}
I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive its like {"primary":"django","success":"Python","seconday":"webApp"}
This is JSON DTL
//Inner for loop for tags
<div class="mb-3">
{% for color,text in Project.tags.items %}
<span class="badge rounded-pill bg-{{ color }}">{{ text }}</span>
{% endfor %}
</div>
Assuming you have a Tag model which is a ManyToManyField, you could just store the color as an attribute to the model.
Your model:
class Tag(models.Model):
text = models.CharField(max_length=32)
color = models.CharField(max_length=32, default="bg-success")
class Project(models.Model):
...
tags = models.ManyToManyField(Tag)
Your template:
{% for tag in Project.tags %}
<span class="badge rounded-pill {{ tag.color }}">{{ tag.text }}</span>
{% endfor %}
Some future improvement to this could be a subclass that pre-defines all of the colors.
Technologies I'm using --> Back-end --> Python, Web Framework --> Django, Front-end --> HTML5, CSS3, Bootstrap 4, Database --> SQLite3.
What I want --> To display the data of each object in each bootstrap's modal box( popup ).
The problem --> Data of the first object is only being shown in all the modal boxes( popups ).
Files are as follows:
HTML template --> manage_requisition.html 👇
{% extends 'hod_template/base_template.html' %}
{% block page_title %}
Manage Requisitions
{% endblock page_title %}
{% block main_content %}
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Manage Requisitions</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<div class="table">
<table class="table">
<tr>
<th style="text-align: center;">Action</th>
<th>View Requisition</th>
</tr>
{% for requisition in requisitions %}
<tr>
<td style="text-align: center; vertical-align: middle;">
{% if requisition.requisition_status == 0 %}
<a style="width: 85px;" href="{% url 'supervisor_approve_requisition' requisition_id=requisition.id %}" class="btn btn-success inline" >Approve</a>
<a style="width: 85px;" class="btn btn-danger inline" href="{% url 'supervisor_rejected_requisition' requisition_id=requisition.id %}" >Reject</a>
{% elif requisition.requisition_status == 1 %}
<button class="btn btn-warning" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Approved</button>
{% else %}
<button class="btn btn-danger" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Rejected</button>
{% endif %}
</td>
<td>
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reqModal">
View Requisition
</button>
<div class="modal" id="reqModal" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="reqModalTitle">Requisition Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p><strong>Position Required :</strong> {{ requisition.position_required }}</p>
<p><strong>Requirement :</strong> {{ requisition.requirement }}</p>
<p><strong>Candidate Name :</strong> {{ requisition.candidate_name }}</p>
<p><strong>Department :</strong> {{ requisition.department }}</p>
<p><strong>Post :</strong> {{ requisition.post }}</p>
<p><strong>Requirement Time Period :</strong> {{ requisition.requirement_time_period }}</p>
<p><strong>Work Type :</strong> {{ requisition.work_type }}</p>
<p><strong>Duration Start Date :</strong> {{ requisition.duration_start_date }}</p>
<p><strong>Duration End Date :</strong> {{ requisition.duration_end_date }}</p>
<p><strong>Requisition Reason :</strong> {{ requisition.requisition_reason }}</p>
<p><strong>Minimum Qualification :</strong> {{ requisition.min_qualification }}</p>
<p><strong>Maximum Qualification :</strong> {{ requisition.max_qualification }}</p>
<p><strong>Minimum Experience :</strong> {{ requisition.min_experience }}</p>
<p><strong>Maximum Experience :</strong> {{ requisition.max_experience }}</p>
</div>
<div class="modal-footer">
</div>
</div>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<!-- Modal -->
<!-- /.content -->
{% endblock main_content %}
Views file --> HODviews.py 👇
def Manage_Requisitions(request):
requisitions = Requisition.objects.all()
context = {"requisitions":requisitions}
return render(request, "hod_template/manage_requisition.html", context)
urls.py file --> urls.py 👇
path("manage_requisition/", HODviews.Manage_Requisitions, name="manage_requisition")
models.py file --> models.py 👇
class Requisition(models.Model):
id = models.AutoField(primary_key=True)
position_required = models.CharField(max_length=2000, default="")
requirement_choices = (
("New", "New"),
("BackFill", "BackFill")
)
requirement = models.CharField(max_length=100, choices=requirement_choices, default="")
candidate_name = models.CharField(max_length=2000, default="")
department = models.CharField(max_length=2000, default="")
post = models.CharField(max_length=2000, default="")
requirement_type = (
("Permanent", "Permanent"),
("Temporary", "Temporary"),
("Fixed Contract", "Fixed Contract")
)
requirement_time_period = models.CharField(max_length=500, choices=requirement_type, default="")
work_type = (
("Full-Time", "Full-Time"),
("Part-Time", "Part-Time")
)
work_type = models.CharField(max_length=500, choices=work_type, default="")
duration_start_date = models.DateField(blank=True)
duration_end_date = models.DateField(blank=True)
requisition_reason = models.TextField()
min_qualification = models.CharField(max_length=1000 ,default="")
max_qualification = models.CharField(max_length=1000 ,default="")
min_experience= models.CharField(max_length=1000 ,default="")
max_experience= models.CharField(max_length=1000 ,default="")
requisition_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.candidate_name
Image of the UI 👇
Image of the first pop up 👇
Image of the second popup 👇
I'm getting the data of first objet in each popup. But I want the data of every object to be displayed in each popup.
You can contact me here 👇
Linkedin --> https://www.linkedin.com/in/precioushuzaifa/
Instagram --> https://www.instagram.com/precious_huzaifa/
The problem is all your modals have the same id and so your buttons are just going to open the first modal they find with the ID. You need to add some sort of id to each modal. you can use {{ forloop.counter }} to get the iteration number and attach that to the id.
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reqModal-{{ forloop.counter }}">
View Requisition
</button>
<div class="modal" id="reqModal-{{ forloop.counter }}" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">
I am always getting all the food items in all Categories.
I want to display each Category with each food item.
Need to display Category with item belonging to that Category.
Please someone help me on this issue to resolve. I have tried looking over internet but couldn't find the solution to it
models.py
class Category(models.Model):
category_name = models.CharField(max_length=50)
def __str__(self):
return self.category_name
class Menu(models.Model):
dish_name = models.CharField(max_length=200, verbose_name='Name of Dish')
Desc = models.TextField(verbose_name='Dish Description')
Amount = models.IntegerField(null=False, blank=False, verbose_name='Amount of Dish')
date_posted = models.DateTimeField(default=timezone.now, verbose_name='Dish Date Posted')
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.dish_name
views.py
def menu(request):
products = Menu.objects.all()
categories = Category.objects.all()
data = {}
data['products'] = products
data['categories'] = categories
template = 'food/menu.html'
return render(request, template, data)
html
{% for category in categories %}
{% if categories %}
<div class="col-xs-12 col-sm-6">
<div class="menu-section">
<h2 class="menu-section-title">{{ category.category_name }}</h2>
<hr>
{% endif %}
{% for i in products %}
<div class="menu-item">
<div class="menu-item-name">{{ i.dish_name}}</div>
<div class="menu-item-price">Rs {{ i.Amount}}</div>
<div class="menu-item-description">{{ i.Desc}}</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
you are not filtering products based on categoris.
I would suggest doing something like this with data:
data = {
'categories': {
category: Menu.objects.filter(category=category) for category in categories
}
}
and in html you can:
{% for category, products in categories.items %}
{% if products %}
<div class="col-xs-12 col-sm-6">
<div class="menu-section">
<h2 class="menu-section-title">{{ category.category_name }}</h2>
<hr>
{% for i in products %}
<div class="menu-item">
<div class="menu-item-name">{{ i.dish_name}}</div>
<div class="menu-item-price">Rs {{ i.Amount}}</div>
<div class="menu-item-description">{{ i.Desc}}</div>
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
My problem is, edit and update the values by using python-flask from client side. I don't have any idea about that and new python-flask using MySQL database. I tried this method for edit and update purpose.But, it's not working.Additionally the details will be added in database when we enter details and submit. anyone help me.
Here is vehicletype.html template.
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype > Create Vehicletype</li>
</ol>
</div>
<div class="row">
<div class="col-md-6">
<form role="form" action="/post/vehicletype" method="post">
<div class="form-group">
<label>VehicleType: </label>
<input name="type" class="form-control" placeholder="enter vehicletype">
</div>
<input type="submit" class="btn btn-primary" value="Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
{% endblock %}
Here is the details.html
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype>View</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
Id
</th>
<th>
VehicleType
</th>
<th>
Dateofsub
</th>
<!--<th>
Control
</th>-->
<th>
Delete
</th>
</tr>
</thead>
{% for values in vehicletype %}
<tr>
<th>{{values.id}}</th>
<td>{{values.type}}</td>
<td>{{values.dateofsub}}</td>
<!--<td>Reset Password</td>-->
<td>Delete</td>
<td>edit</td>
</tr>
{% endfor %}
</table>
<em class="fa fa-xl fa-plus-circle color-blue" ></em>
</div>
</div>
{% endblock %}
python code for Edit method:
class VehicetypeForm(FlaskForm):
type=StringField('Type')
#app.route('/control/edit/<int:id>',methods=['POST','GET','PATCH'])
def edit(id):
form = VehicetypeForm(request.form)
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur = mysql .cursor()
cur.execute('SELECT * FROM vehicletype WHERE id= %s',[id])
type=cur.fetchall()
# form.type.data=type
if request.method=='PATCH' and form.validate():
#type=form.type.data
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur=pymysql .cursor()
cur.execute('UPDATE vehicletype SET type=%s WHERE id=%s',(type,id))
mysql.connection.commit()
cur.close()
flash('success')
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html',form=form)
In this python code update method is not working. But, when we give the details that details will be added in database. How to edit and update the values from client side.
Below is the good practice to create form using wtforms
class UserForm(Form):
name = StringField('Name')
father_name = StringField('Father Name')
# .... add fields you want
for field types - refer to this link
#app.route('/newuser', methods=['GET', 'POST'])
def add_user():
form = UserForm()
if form.validate_on_submit():
user_details = {
name: form.name.data,
fathername: form.father_name.data,
# add more fields
}
sqlsession.add(user_details)
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)
Once you have form then you can easily edit your content and directly save it to database
#app.route('/control/edituser/<int:id>',method=['post','get'])
def edit(id):
qry=sqlsession.query(Enduser).filter(Enduser.id==id).first()
form = UserForm(request.form, **qry)
if form.validate_on_submit():
form.populate_obj(qry)
sqlsession.update(qry)
sqlsession.commit()
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)