Django parent.child_set no errors but not showing in html - django-views

Views.py defining the context in view
def customers(request, pk):
customer = Customer.objects.get(id=pk)
issues = customer.issue_set.all()
receives = customer.receive_set.all()
context={'customer':customer,'issues':issues,'receives':receives}
return render(request,'accounts/customers.html')
in html
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
{% for issue in issues %}
<td>{{issue.item}}</td>>
<td>{{issue.item.category}}</td>
<td>{{issue.date_created}}</td>
<td>{{issue.status}}</td>
<td><a href="">UPDATE</td>
<td><a href="">DELETE</td>
{% endfor %}
#Model
class Item(models.Model):
CATEGORY = (
('Gudang Kering', 'Gudang Kering'),
('Gudang Basah','Gudang Basah'),
)
name = models.CharField(max_length=200,null= True)
stock = models.IntegerField(default='0', blank=False, null=True)
category = models.CharField(max_length=200,null= True,choices=CATEGORY)
reorderlevel = models.IntegerField(default='0', blank=False, null=True)
maxreorderlevel = models.IntegerField(default='0', blank=False, null=True)
description = models.CharField(max_length=200,null= True, blank= True)
date_created = models.DateTimeField(auto_now_add= True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Issue(models.Model):
STATUS = (
('Pending', 'Pending'),
('Granted','Granted'),
('Denied','Denied'),
)
customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
item = models.ForeignKey(Item, null=True, on_delete= models.SET_NULL)
quantity = models.IntegerField(default='0', blank=False, null=True)
date_created = models.DateTimeField(auto_now_add=True, auto_now=False)
status = models.CharField(max_length=200,null= True, choices=STATUS)
def __str__(self):
return self.status + ' ' +str(self.customer)
I tried to get the object by id of the customer in order to make it a dynamic url where the url will depend on str:pk of customer id
i managed to show output data if i do
customer = Customer.objects.all #but that will show all the customer
so i tried as in the view to get the id
and define it with parent.child_set.all
but it doesn't show up,even the text update and delete don't show up in

Related

Show all items of an invoice - django

I would like to get all items belonging to an invoice and show them to a template without success. What i have done so far is the following:
I have two models:
class Invoice(models.Model):
PAYMENT_OPTIONS = (
('CASH', _('CASH')),
('DEPOSIT', _('DEPOSIT')),
('CARD', _('CARD')),
)
INVOICE_TYPE = (
('Service', _('Service')),
)
invoice_number = models.CharField(max_length=7, unique=True, default='INV4898')
invoice_user = models.ForeignKey(Account, on_delete=models.CASCADE)
invoice_type = models.CharField(max_length=30, choices=INVOICE_TYPE, default='Service')
payment_option = models.CharField(max_length=30, choices=PAYMENT_OPTIONS)
invoice_name = models.CharField(max_length=30, null=True, blank=True)
vat = models.CharField(max_length=9, blank=True, null=True)
gross_amount = models.DecimalField(max_digits=6, decimal_places=2)
vat_amount = models.DecimalField(max_digits=6, decimal_places=2)
net_amount = models.DecimalField(max_digits=6, decimal_places=2)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice_user.first_name} {self.invoice_user.last_name} - {self.invoice_number}"
class Item(models.Model):
invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
quantity = models.IntegerField(default=1)
unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
net_amount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
vat_rate = models.CharField(max_length=10, default=0)
discount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
is_paid = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice.invoice_number}"
In the views.py i have a list view like, in which i'm trying to get a list of all invoices based on invoice_number and then match each invoice_number to an invoice in items. However using below code first pring brings all invoice_number(s) and second print brings all items for all invoices, not items per invoice.
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices =Invoice.objects.filter(invoice_user=user_profile)
invoice_number = Invoice.objects.values_list('invoice_number')
print(invoice_number)
item_invoice = Item.objects.filter(invoice__invoice_number__in=invoice_number)
print(item_invoice)
context = {
'all_invoices': all_invoices,
'user_profile': user_profile,
'item_invoice': item_invoice,
}
return render(request, 'invoices/list-invoices.html', context)
I would appreciate any help.
You do not need to fetch the Items not the invoice_number of the Invoice. You only need to pass the invoices of the user_profile, and it might be better to also prefetch the Items:
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices = Invoice.objects.filter(
invoice_user=user_profile
).prefetch_related('items')
context = {
'all_invoices': all_invoices,
'user_profile': user_profile
}
return render(request, 'invoices/list-invoices.html', context)
then in the template, you can access the .items, so:
<ul>
{% for invoice in all_invoices %}
<li> {{ invoice.invoice_number }}</li>
<ul>
{% for item in invoice.items.all %}
<li>{{ item.quantity }} {{ item.title }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>

Django How to get the value from many to many relationship

I have a product update form where I want to update the sizes of a product, with a many-to-many column relation.
I am able to get the saved values but I can't get item ID or size.
{{item.id}} shows empty value.
{% for item in form.size.value %}
<span>
<input type="checkbox" name="size" id="{{ item.id }}" value="{{ item.id }}">
<label for="{{ item.id }}">{{ item }}</label>
</span>
{% endfor %}
SIZE MODEL
class Size(models.Model):
identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
size = models.CharField(max_length=200, unique=True, null=False, blank=False)
active = models.BooleanField(default=True)
date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True)
date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True)
PRODUCT MODEL
class Product(models.Model):
identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=200, null=False, blank=False)
slug = models.SlugField(max_length=30, unique=True)
showcased = models.BooleanField(default=False)
recommended = models.BooleanField(default=False)
active = models.BooleanField(default=True)
price = models.DecimalField(max_digits = 5, decimal_places = 2, null=True, blank=True)
pagetitle = models.CharField(max_length=200, null=True, blank=True)
shortDescription = models.CharField(max_length=200, null=True, blank=True)
longDescription = HTMLField(null=True, blank=True)
specifications = models.TextField(null=True, blank=True)
features = models.TextField(null=True, blank=True)
care = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
subCategory = models.ForeignKey(SubCategory, null=True, blank=True, on_delete=models.PROTECT)
image = models.ManyToManyField(Image, blank=True)
size = models.ManyToManyField(Size, blank=True)
tag = models.ManyToManyField(Tag, blank=True)
date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True)
date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True)
I have tried different ways but not had success in getting the name or id
def updateProduct(request, pk):
categories = Category.objects.all()
sizes = Size.objects.all()
tags = Tag.objects.all()
product = Product.objects.get(id=pk)
subCategories = SubCategory.objects.filter(category=product.category.id)
images = product.image.all()
if request.method == 'POST':
form = ProductForm(request.POST, instance=product)
if form.is_valid():
form.save()
return redirect('product-panel')
form = ProductForm(instance=product)
return render(request, 'public/views/backend/product-update.html', {'categories':categories,'subCategories':subCategories, 'sizes':sizes, 'tags':tags, 'form':form, 'images':images})

Django search vector - no match on exact keyword

I have an application where customer can search for products by name, brand etc.
the problem is if you write the exact name or the exact brand name will result in no match,
if you write the half of the name or the id will return a match
view
def home(request):
active_product = Product.objects.all().filter(show=True).order_by('-score', '-brand_name')
#Paginator
paginator = Paginator(active_product, 20)
page = request.GET.get("page")
active_product = paginator.get_page(page)
#Filterd by search
searchProduct = request.GET.get("do_search")
if searchProduct:
active_product = Product.objects.annotate(search=SearchVector('name', 'id', 'sex','brand_name'),).filter(search__icontains=searchProduct)
return render(request, 'index.html', {'productObject': active_product})
Model:
class Brand(models.Model):
name = models.CharField(unique=True, max_length=30, blank=False,null=True)
def __str__(self):
return self.name
class Product(models.Model):
genderChoice = (('W','Female'),('M','Male'),('U','Unisex'))
id = models.BigIntegerField(primary_key=True, null=False)
brand_name = models.ForeignKey(Brand, to_field='name', on_delete=models.CASCADE, related_name='brand_name', default='Brand Name')
name = models.CharField(max_length=300, blank=False,null=False)
sex = models.CharField(max_length=7,choices=genderChoice, default='U')
p_type = models.CharField(max_length=50, blank=True,null=True)
image_link = models.CharField(max_length=500, blank=True,null=True)
stock_price = models.DecimalField(max_digits=10,decimal_places=2, default=999.00)
show = models.BooleanField(default=False)
in_stock = models.BooleanField(default=False)
created = models.DateField(auto_now_add=True)
volume= models.CharField(max_length=50, blank=True,null=True)
score = models.IntegerField(default=1)
price = models.DecimalField(max_digits=100, default=999.00, decimal_places=2)
def __str__(self):
template = '{0.name} {0.brand_name} {0.volume} {0.price}'
return template.format(self)
html:
<form class="my-2 my-lg-0" action="{% url 'home'%}" method="GET">
<div class="input-group mb-3">
<input type="search" class="form-control border-dark" placeholder="search" aria-label="Search" aria-describedby="button-addon2" name="do_search">
<button class="ml-1 btn btn-outline-dark" type="submit" id="button-addon2">Search</button>
The way you use searchvector is wrong. According to the doc about searchvector
replace:
active_product = Product.objects\
.annotate(search=SearchVector('name', 'id', 'sex','brand_name'),)\
.filter(search__icontains=searchProduct)
with
active_product = Product.objects\
.annotate(search=SearchVector('name', 'id', 'sex','brand_name'))\ # no need to have another ","
.filter(search=searchProduct) # remove icontains

Django odd boolean bahavior

I have a boolean field for whether or not an item is active:
is_active = models.BooleanField(default=True)
It seems pretty straightforward, my template will display items that are active:
{% for p in products|dictsortreversed:"id" %}
{% if p.is_active %}
<a href="{{ p.get_absolute_url }}">
{{ p.name }}
</a>
{% endif %}
For some reason all items are returned even if the field is 0 in the database. When I uncheck the boolean field in the django admin, it updates correctly to 0 in the database, but still shows as being checked in the admin...
It seems like django is reading the field as True, regardless of the boolean value.
Model
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name')
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
image = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField('Meta Keywords', max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField('Meta Description', max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ForeignKey(Category, null=True)
publish_date = models.DateField(blank=True, null=True)
issue_one = models.CharField(blank=True, null=True, max_length=255)
issue_two = models.CharField(blank=True, null=True, max_length=255)
issue_three = models.CharField(blank=True, null=True, max_length=255)
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
View:
def index(request, template_name="catalog/index.html"):
""" site home page """
page_title = 'Visible Language Ordering'
return render_to_response(template_name, locals(), context_instance=RequestContext(request))

Display ForeignKey attributes in template

I have the following models:
# models.py
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
class SiteRatings(models.Model):
site = models.ForeignKey('Site', related_name='siterating', blank=True, null=True)
overall_rating = models.FloatField(blank=True, null=True)
plans_rating = models.FloatField(blank=True, null=True)
prices_rating = models.FloatField(blank=True, null=True)
design_rating = models.FloatField(blank=True, null=True)
support_rating = models.FloatField(blank=True, null=True)
def save(self, *args, **kwargs):
self.overall_rating = (self.plans_rating + self.prices_rating + self.design_rating + self.support_rating)/4
super(SiteRatings, self).save(*args, **kwargs)
def __str__(self):
return self.site.name
My views
# views.py
def home(request):
print(user_language)
site_list = Site.objects.order_by('-date_launched')
return render_to_response('index.html', {'site_list': site_list}, RequestContext(request))
In template
# template
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.siterating.overall_rating }}</span></h4>
{% endfor % }
The problem is that when I try to access {{ site.siterating.overall_rating }} nothing is being returned, I tried to change for {{ site.siterating.0.overall_rating }} and it is not displaying yet.
I solved my problem. First in models I created a method to get the site rating (thank you karthikr for your suggestion):
#models
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
def get_site_rating(self):
return self.siterating.filter(site = self)
After, I went to my template and used the class method that I had created:
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.get_site_rating.0.overall_rating }}</span></h4>
{% endfor % }
Please, note that I used ...get_site_rating.0... just because in my case I have just 1 rating/site.