How to autocomplete input in field Django - python

I have a product model. I need to autocomplete product name into input field. How can I code?
class Product(models.Model):
product_name = models.CharField(max_length=255)
product_detail = models.TextField(blank=True, null=True)
product_price = models.FloatField(blank=True)
category = models.CharField(max_length=30)
product_image = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=255, blank=True, null=True)
product_amount = models.IntegerField(blank=True, null=True)
del_flag = models.BooleanField(default=False)
def __str__(self):
return self.product_name

Related

How can i display the category for a particular product in the product list page? - Django

I am trying to display a product list page with products attributes along with category which is a MPTT field. I want to display the category assigned to that particular product in the product list page. How can i achieve this?
Models
class Category(MPTTModel):
"""
Inventory Category table implimented with MPTT
"""
name = models.CharField(
max_length=100,
null=False,
unique=False,
blank=False,
verbose_name=_("category name"),
help_text=_("format: required, max-100"),
)
slug = AutoSlugField(populate_from='name')
cat_img = models.ImageField(upload_to='images/categories/')
parent = TreeForeignKey(
"self",
on_delete=models.PROTECT,
related_name="children",
null=True,
blank=True,
unique=False,
verbose_name=_("parent of category"),
help_text=_("format: not required"),
)
class MPTTMeta:
order_insertion_by = ["name"]
class Meta:
verbose_name = _("product category")
verbose_name_plural = _("product categories")
def __str__(self):
return self.name
class Product(models.Model):
"""
Product details table
"""
product_id = models.UUIDField(default=uuid.uuid4, editable=False)
sku = models.CharField(max_length=255, blank=True, null=True)
name = models.CharField(
max_length=255,
unique=False,
null=False,
blank=False,
verbose_name=_("product name"),
help_text=_("format: required, max-255"),
)
slug = AutoSlugField(populate_from='name')
price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
description = models.TextField(
unique=False,
null=True,
blank=True,
verbose_name=_("product description"),
help_text=_("format: required"),
)
prd_img = models.ImageField(upload_to='images/products/', null=True, blank=True)
category = TreeManyToManyField(Category, null=True, blank=True)
modifier_group = models.ManyToManyField(ModifierGroup, null=True, blank=True)
def __str__(self):
return self.name
Views
#login_required(login_url='/login/')
def productList(request):
products = Product.objects.all()
context = {'products':products}
template = 'product/product/products.html'
return render(request,template,context)
Template
<td class="text-end pe-0" data-order="37">
<span class="fw-bold ms-3">{{product.category.name}}</span>
</td>
Template Result
How can i query and display the category for that particular product in the product list page?

Django _set.all() filter in QuerySet

I have database and I want to extract specific data of specific user from queryset. Now i have this
VIEW
def index(request):
customerByName = Customer.objects.get(name='pablo')
shopListById = ShopList.objects.get(transaction_id=1)
shpoListSpecific = customerByName.shoplist_set.all()
specificProducts = shopListById.shoplistproduct_set.all()
context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById,
'specificProducts': specificProducts}
return render(request, 'QuickShopperApp/home.html', context)
MODELS
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
device = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
if self.name:
name = self.name
else:
name = self.device
return str(name)
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class ShopList(models.Model): # cart
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
#product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.product)
template.html
<h3>specificProducts: {{specificProducts}}</h3>
On my side i see items of specific customer.
specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]>
How can i get only Apple, Cucumber, Cucumber?
try this
'specificProducts': specificProducts.values_list('product__name')
or
'specificProducts': list(specificProducts.values_list('product__name', flat=True))
https://docs.djangoproject.com/en/3.1/ref/models/querysets/#values-list

How to access other model fields through foreign key in Django Views

I want to query from OrderItem Model like
total_orders = OrderItem.objects.filter(product.user == request.user.id).count()
but i am getting error
**
NameError at /home
name 'product' is not defined
**
MY MODELS:
Product Model:
class Product(models.Model):
title = models.CharField(max_length=150)
user = models.ForeignKey(
User, blank=True, null=True, on_delete=models.SET_DEFAULT, default=None)
description = models.TextField()
price = models.FloatField()
quantity = models.IntegerField(default=False, null=True, blank=False)
minorder = models.CharField(
max_length=150, help_text='Minum Products that want to sell on per order', null=True, default=None, blank=True)
image = models.ImageField()
category = models.ForeignKey(
Categories, default=1, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
def __str__(self):
return self.title
Order Item Model
class OrderItem(models.Model):
product = models.ForeignKey(
Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(
Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.FloatField(default=0, null=True, blank=True)
date_orderd = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
price = models.FloatField(blank=True, null=True)
def __str__(self):
return str(self.product)
My View:
def home(request):
total_orders = OrderItem.objects.filter(
product.user == request.user.id).count()
return render(request, "sellerprofile/home.html", {'total_orders': total_orders})
Do:
total_orders = OrderItem.objects.filter(product__user=request.user).count()
You can look at the documentation here about field lookups on more detail.

Accessing a parent's model attributes from child model in django

please can anyone help me out am stuck i want to access items in the item model which i have referenced in the OrderItem model but am trying to access the item from Order model
here are the models
here is the model that am using to access
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
ref_code = models.CharField(max_length=20)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
order_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
shipping_address = models.ForeignKey('Address',on_delete=models.SET_NULL,related_name='shipping_address',blank=True,null=True)
payment = models.ForeignKey('Payment',on_delete=models.SET_NULL,blank=True,null=True)
being_delivered = models.BooleanField(default=False)
received = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
Here is the parent model which i want to access
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
ordered_order = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
and the item am trying to access must in this model
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.IntegerField()
discount_price = models.IntegerField(blank=True, null=True)
category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING)
tags = models.ManyToManyField(Tags, related_name='itemTags')
slug = models.SlugField(max_length=200, unique=True)
size = models.CharField(blank=True, null=True, max_length=5)
model = models.CharField(max_length=100, blank=True, null=True)
description = models.TextField()
quantity = models.IntegerField(default=1)
image = models.ImageField()
color = models.CharField(max_length=100, blank=True, null=True)
brand = models.CharField(max_length=100, blank=True, null=True)
Display = models.DecimalField(max_digits=100,
decimal_places=1,
blank=True,
null=True)
ram = models.CharField(max_length=100, blank=True, null=True)
material = models.CharField(max_length=100, blank=True, null=True)
hdd = models.CharField(max_length=100, blank=True, null=True)
size = models.CharField(max_length=100, blank=True, null=True)
lens = models.CharField(max_length=100, blank=True, null=True)
created_at = models.DateField(auto_now_add=True)
i was trying with this but seem not to work
recent_orders=Order.objects.filter(user=2)
for item in recent_orders:
print(item.items.item.title)
can anyone help me out Please!!!
You need thi code:
recent_orders=Order.objects.filter(user=2)
for order in recent_orders:
for order_item in order.items:
print(order_item.item.title)
try to give different names to all your variables, this will make programming more effective

how can i display average of time spent (in_time and out_time) in django? do i use aggregation?

I am new to django and i am facing a problem in displaying the average of time
My database model is
from django.db import models
class Employee(models.Model):
class Meta:
db_table = 'Employee'
emp_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
department_id = models.IntegerField(blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class AttendanceRecord(models.Model):
class Meta:
db_table = 'AttendanceRecord'
emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE)
# emp_id = models.CharField(max_length=100, blank=True, null=True)
date = models.CharField(max_length=100, blank=True, null=True)
miti = models.CharField(max_length=100, blank=True, null=True)
day = models.CharField(max_length=100, blank=True, null=True)
in_time = models.CharField(max_length=100, blank=True, null=True)
out_time = models.CharField(max_length=100, blank=True, null=True)
punch_count = models.IntegerField(blank=True, null=True)
time_spent = models.FloatField(blank=True, null=True)
difference_time = models.FloatField(blank=True, null=True)
def __str__(self):
return self.emp_id.name
class Department:
class Meta:
db_table = 'Department'
department_id = models.IntegerField(primary_key=True)
staff_count= models.IntegerField()
My Report view is:
I want to average the in_time so that i can average it and display in the report template. i cant figure out how.
from attendance.models import AttendanceRecord
class Report:
def get_all_employee_data(from_date, to_date):
all_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date).order_by(
'-miti')
return all_employee_list
def get_specific_emp_data(from_date, to_date, e_id):
specific_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date,
emp_id=e_id).order_by('-miti')
return specific_employee_list
My test data looks like this
TEST DATA

Categories