Not getting the value in django template - django

models.py
class Stock(models.Model):
name = models.CharField(verbose_name='Name of Stock', max_length=300)
purchase_price = models.DecimalField(verbose_name='Purchase Price', blank=True, null=True, max_digits=30, decimal_places=2)
pre_price = models.DecimalField(verbose_name='Last Day Price', blank=True, null=True, max_digits=30, decimal_places=2)
current_price = models.DecimalField(verbose_name='Current Price', blank=True, null=True, max_digits=30, decimal_places=2)
def __str__(self):
return self.name
class StockList(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
stock = models.ForeignKey(Stock)
quantity = models.IntegerField(verbose_name='No.of Shares',default=0)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return str(self.stock)
def market_value_reciever(sender, instance, *args, **kwargs):
purchase_price = instance.stock.purchase_price
quantity = instance.quantity
market_value = purchase_price * quantity
instance.market_value = market_value
print(purchase_price)
print(market_value)
pre_save.connect(market_value_reciever, sender=StockList)
html template
{% for item in queryset %}
<tr>
<td>
{{ item.stock.name }}
</td>
<td>
{{ item.purchase_price }}
</td>
<td>
{{ item.quantity }}
</td>
<td>
{{ item.market_value }}
</td>
</tr>
{% endfor %}
Here I am getting only the value of quantity on html template, purchase price and market value fields are not getting on templates but its values are getting on terminal. Anybody can help, Thank you so much.

You could use the #property decorator in StockList model, so the template can render it:
class StockList(models.Model):
#property
def purchase_price(self):
return self.stock.purchase_price
#property
def market_value(self):
return self.purchase_price * self.quantity

Related

Multiply Django field values to get a total

I have the following models:
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.supplier.name
#property
def total(self):
orderitems = self.product_set.all()
total = sum([item.get_total for item in products])
return total
class Product(models.Model):
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(
null=True, max_length=99, unique=True, blank=True)
supplier = models.ForeignKey(
Supplier, on_delete=models.CASCADE, default=5)
on_order = models.ForeignKey(
Order, on_delete=models.CASCADE, null=True, blank=True)
on_order_quantity = models.FloatField(null=True, blank=True)
class Meta:
ordering = ('description',)
def __str__(self):
return self.description
i've created an order object for a given supplier with two products, with different quantities and cost prices.
How do I multiply cost x qty and add up those values in order to reach a total order value?
this is my view
def PurchaseOrder(request, pk_order):
orders = Order.objects.get(id=pk_order)
products = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_products = products.count()
supplier = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_value = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('costprice'))
context = {
'supplier': supplier,
'products': products,
'orders': orders,
'total_products': total_products,
'total_value': total_value, }
return render(request, 'crmapp/purchase_order.html', context)
at the moment it returns this:
This is my html template
It looks like your post is mostly code; please add some more details.'
Well, I need to show my code
{% extends 'crmapp/base.html' %}
{% load static %}
{% block content %}
<div class='main-site>'>
<h4> Supplier: {{orders.supplier}}</h4>
<h5>Order Number: {{orders.id}}</h5>
<h5>Created on: {{orders.date_created | date:"d/m/Y"}}</h5>
<h6>Total Lines In Order: {{total_products}}</h6>
<button style='margin-bottom:10px' class='btn btn-primary' id="open-popup-1">Edit</button>
<button style='margin-bottom:10px' class='btn btn-success' href="" id="open-popup-1">Print/Export</button>
<input type="search" placeholder="Search any field..." class="form-control search-input" data-table="customers-list"/>
<table class="table table js-sort-table mt32 customers-list" id='myTable'>
<thead class="table" >
<tr>
<th class='header' onclick="sortTable(0)" scope="col">ID</th>
<th class='header' onclick="sortTable(1)" scope="col">Description</th>
<th class='header' onclick="sortTable(3)" scope="col">Order Quantity</th>
<th class='header' onclick="sortTable(2)" scope="col">Cost</th>
</tr>
</thead>
<tbody>
<tr>
{% for product in products %}
<td> {{product.id}}</td>
<td><h6><strong>{{product.description}}</strong></h6></td>
<td>{{product.on_order_quantity |floatformat:0}}</td>
<td>£{{product.costprice |floatformat:2}}</td>
</tr>
</tbody>
{% endfor %}
</table>
<div class='ordertotal'>
<h5>Order Value:</h5>
<h6><strong>{{total_value}}</strong></h6>
</div>
</div>
{% endblock %}
Use the property decorator for the costprice field in the Product Model?
class Product(models.Model):
# define other fields here
#property
def costprice(self):
"Returns retailprice * qty for each product."
return self.on_order_quantity * self.retailprice
Update:
There's clearly some misunderstanding. Therefore I'll try to provide more information.
First Question: "How do I multiply cost x qty"
The property decorator allows you to create fields, which behave like calculated read_only fields. (You don't need to initialize them)
#property
def cost_x_qty(self):
"Returns costprice multiplied by qty for each product."
return self.on_order_quantity * self.costprice
Second Question: "How do I add up those values in order to reach a total order value?"
You can use Aggregation to do this.
You can do the following in your view function:
def PurchaseOrder(request, pk_order):
# some code
grand_total = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('cost_x_qty'))
# add to context
context['grand_total'] = grand_total
return render(request, 'some_template.html', context)
you can use the grand_total in your template file like this:
{{grant_total}}
Hope that helps

Reverse lookup on template page not working

I have a contact and an event model where the event model has a foreign key to contact. The first half of my html obviously works, but for some reason when I display the list of other events that the contact has done, I can't get the list to show up. Is it because I'm calling {{event.whatever}} twice on the same page but in two differrent context?
views.py
class EventDetail(DetailView):
template_name = 'crm/eventdetail.html'
model = Event
models.py
class Contact(models.Model):
firstname = models.CharField(max_length=20, null=True, blank=True)
lastname = models.CharField(max_length=20, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=20, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["lastname"]
def __str__(self):
return self.firstname
class Event(models.Model):
event_type = models.CharField(max_length=20, choices = event_types)
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
should_follow_up = models.BooleanField(default=False)
date = models.DateField()
notes = models.CharField(max_length=400)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('events_detail', kwargs={'pk': self.pk})
eventdetail.html
<div id="container">
<h1> Event: {{event.event_type}} </h1>
<ul>
<li>Event Contact: {{event.contact}}</li>
<li>Created By: {{event.created_by}}</li>
<li>Date: {{event.date}}</li>
<li>Note: {{event.notes}}</li>
</ul>
<h1>Events for {{event.contact}}</h1>
<table class="table">
<tr>
<th scope="col">Event Type</th>
<th scope="col">Date</th>
<th scope="col">3</th>
</tr>
{% for event in contact.event_set.all %}
<tr>
<td> {{event.event_type}}</td>
<td> {{event.date}}</td>
<td> </td>
</tr>
{% endfor %}
</table>
<p>This event was inputted on {{event.created}} and last edited on {{event.updated}}</p>
</div>
The for loop which is supposed to display all the other events the contact has done is not showing up. Any help is appreciated
Changes my view
class EventDetail(DetailView):
def get(self, request, *args, **kwargs):
event = get_object_or_404(Event, pk=kwargs['pk'])
events = event.contact.eventss.all()
context = {'event': event, 'events':events}
return render(request, 'crm/eventdetail.html', context)
Added a related_name to my model
contact = models.ForeignKey(Contact, related_name='eventss', on_delete=models.CASCADE)
Here is the html file that finally worked
{% for events in event.contact.eventss.all %}
<tr>
<td>{{events.event_type}}</td>
<td>{{events.date}}</td>
<td> </td>
</tr>
{% endfor %}

how to show foreign key value instead of its ID

i'm try to display foreign key value , but it instead return the id , in template
models.py
class Product(models.Model):
product_name = models.CharField(unique=True, max_length=50)
pass
def __str__(self):
return self.product_name
class Order(models.Model):
id = models.AutoField(primary_key = True)
products = models.ManyToManyField(Product ,through='ProductOrder')
pass
def __str__(self):
return str(self.products.all())
class ProductOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
ordering = models.ForeignKey(Order,
on_delete=models.CASCADE,blank=True,null=True)
pass
def __str__(self):
return str(self.product)
this is my views.py
class ListOfOrder(ListView):
template_name = 'order/product_group.html'
context_object_name = 'productss'
def get_queryset(self):
return ProductOrder.objects.all()
template.html
{% for product in productss %}
<tr class="">
<td style="text-align: center;">{{ product.product }}</td>
{% endfor %}
i expected to display the product name but it instead displayed the ID of the product
thanks for your answer

Handling one to one relationship between django models

I am having a one to one relationship between 2 models. While creating the second model, I want to pass the instance of the first model to the second one.
These 2 models are new tabs/features in our web application. I tried passing the instance through URL but didn't succeed. Maybe I am not following steps correctly.
Details about:
python version: Python 3.6.4 :: Anaconda, Inc.
django version: 2.0.2-3
Please find below the code:
1) models.py
class StudyConcept(models.Model):
requestor_name = models.CharField(max_length=240, blank=False, null=False)
project = models.CharField(max_length=240, blank=False, null=False)
date_of_request = models.DateField(blank=False, null=False)
brief_summary = models.CharField(max_length=4000, blank=False, null=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class Logistics(models.Model):
budget = models.CharField(max_length=255, blank=False, null=False)
business_technology = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
vendor_or_contracts = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
studyConcept = models.OneToOneField(StudyConcept, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
def get_absolute_url(self):
return reverse('update_Logistics', kwargs={'pk': self.pk})
def get_deliverablesLogistics(self):
return ','.join([str(i) for i in self.deliverablesLogistics.all().values_list('id', flat=True)])
def get_paymentScheduleLogistics(self):
return ','.join([str(i) for i in self.paymentScheduleLogistics.all().values_list('id', flat=True)])
def get_commentsLogistics(self):
return ','.join([str(i) for i in self.commentsLogistics.all().values_list('id', flat=True)])
class DeliverablesLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
poa = models.CharField('POA', max_length=480, blank=False, null=False)
start_date = models.DateField(blank=False, null=False)
end_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='deliverablesLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class PaymentScheduleLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
cost = models.DecimalField(max_digits=14, decimal_places=2, blank=False, null=False, default=0)
estimated_payment_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='paymentScheduleLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class CommentsLogistics(models.Model):
comments = models.CharField('Comment', max_length=2000, blank=True, null=True)
commented_by = models.CharField(max_length=2000, blank=True, null=True)
logistics = models.ForeignKey(Logistics, related_name='commentsLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
views.py
def load_concepts(request):
currentUser = User.objects.get(id=request.user.id)
concepts = StudyConcept.objects.all().filter(user=request.user)
#concepts = get_object_or_404(StudyConcept)
return render(request, 'concept_dropdown_list_options.html',{
'concepts':concepts
})
class LogisticsFormsetCreate(CreateView):
model = Logistics
template_name = 'createLogistics.html'
form_class = LogisticsForm
success_url = reverse_lazy('create_Logistics')
def get_context_data(self, **kwargs):
data = super(LogisticsFormsetCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['deliverable'] = DeliverablesLogisticsFormset(self.request.POST, prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(self.request.POST, prefix='payments')
data['comment'] = CommentsLogisticsFormset(self.request.POST, prefix='comments')
#data['studyRequestConcept'] = self.request.POST.get('studyRequestConcept')
else:
data['deliverable'] = DeliverablesLogisticsFormset(prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(prefix='payments')
data['comment'] = CommentsLogisticsFormset(prefix='comments')
#data['studyRequestConcept'] = self.request.GET.get('studyRequestConcept')
return data
def form_valid(self, form):
context = self.get_context_data()
deliverable = context['deliverable']
paymentSchedule = context['paymentSchedule']
comment = context['comment']
with transaction.atomic():
if deliverable.is_valid() and paymentSchedule.is_valid() and comment.is_valid():
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object = form.save()
deliverable.instance = self.object
deliverable.save()
paymentSchedule.instance = self.object
paymentSchedule.save()
comment.instance = self.object
comment.save()
messages.success(self.request, Logistics.__name__ +' Form ID: '+ str(self.object.id) + ' was submitted successfully')
return super(LogisticsFormsetCreate, self).form_valid(form)
else:
return self.render_to_response(self.get_context_data(form=form))
Template
{% extends "header.html" %}
{% load widget_tweaks %}
{% block content %}
{% csrf_token %}
{% include 'xdsoft_stylesheets.html' %}
{% include 'messages.html' %}
<div class="container" align="center">
<h1 class="display-5">Logistics</h1>
</div>
<br/>
<div class="table-responsive">
<table class="table table-striped table-bordered" id="example" data-toggle="table"
data-filter-control="true" data-show-export="true"
data-click-to-select="true" data-toolbar="#toolbar" data-escape>
<thead>
<tr>
<th></th>
<th class="text-center" data-field="id" data-filter-control="input">ID</th>
<th class="text-center" data-field="project" data-filter-control="input">Project</th>
<th class="text-center" data-field="date_of_request" data-filter-control="input">Date</th>
<th class="text-center" data-field="brief_summary" data-filter-control="input">Summary</th>
<th class="text-center" data-field="scientific_question" data-filter-control="input">Question</th>
</tr>
</thead>
<tbody>
{%for studyRequestConcept in concepts %}
<tr>
<td style="width:200px">
<a class=" btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' %}">
<span class="glyphicon glyphicon-plus"></span>
New Logistics
</a>
</td>
<td class="text-left">{{studyRequestConcept.id}}</td>
<td class="text-left">{{studyRequestConcept.project}}</td>
<td class="text-left">{{studyRequestConcept.date_of_request}}</td>
<td class="text-left">{{studyRequestConcept.brief_summary}}</td>
<td class="text-left">{{studyRequestConcept.scientific_question}}</td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
{% comment %}The modal container{% endcomment %}
<div class="modal" id="modal" data-backdrop="false"></div>
<script>
$(function () {
$('.js-create-logistics').click( function () {
var btn = $(this)
$.ajax({
url: btn.attr("href"),
context: document.body
}).done(function(response) {
$("#modal").html(response);
});
});
});
</script>
{% endblock %}
I have a view/template where I list all the Study Concepts and every row has a create new Logistics button next to it. After clicking create new logistics button, the modal/view will open that will allow you to create a new Logistics. I want to pass the instance of the object study concept when I click the button.
Also, CreateLogistics is a class-based view designed using "from django.views.generic import CreateView"
I will be more than happy to provide any further code or information needed. Thanks in advance for all the support and help.
Regards,
Amey Kelekar
You haven't shown your URLs, but you need to accept the ID in the URL for the CreateView and use it in form_valid. For example:
path('/create_logistics/<int:id>/', LogisticsFormsetCreate.as_view(), name="create_Logistics"),
So in the template you would do:
<a class="btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' id=studyRequestConcept.id %}">
and in the view:
def form_valid(self, form):
...
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.studyConcept_id = self.kwargs['id']
self.object.save()
...

How to get image connected by Foreign Key via Template in django

i want to get the images form the image model in the template.
class Products(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
class Image(models.Model):
property = models.ForeignKey(Products, related_name='images')
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html',
locals(),
context_instance=RequestContext(request))
{% for query in queryset %}
<img src='/ {{ query.????? }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
i want to get the images which is connected to that product
i have readed that link
i have tried:
{% for query in queryset %}
<img src='/ {{ query.images_all.0.image }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
but no success ..
just try to understand the model that how i get the image url from models which related with foreignkey relationship.
my models:
class Product(models.Model):
title = models.CharField(max_length = 400)
slug = models.SlugField(max_length = 400,unique=True,null=True,blank=True)
is_popular = models.BooleanField(default=True)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
subcategory = models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True,blank=True)
childcategory = models.ForeignKey(Childcategory,on_delete=models.CASCADE,null=True,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE,null=True,blank=True)
description = models.TextField()
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = unique_slug_generator(self)
super(Product, self).save(*args, **kwargs)
def show_image(self):
return self.productmeaserment_set.first().first_image()
class ProductMeaserment(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
measerment = models.ForeignKey(Measerment,on_delete=models.CASCADE,null=True,blank=True)
selling_price = models.DecimalField(max_digits=20,decimal_places=2)
offer_price = models.DecimalField(max_digits=20,decimal_places=2)
available_quantity = models.IntegerField();
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.measerment.name
def first_image(self):
return self.productmeasermentimage_set.first()
class ProductMeasermentImage(models.Model):
productmeaserment = models.ForeignKey(ProductMeaserment,on_delete=models.CASCADE)
image = models.FileField(upload_to='uploads/products')
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.productmeaserment.product.title
views.py
from products.models import Product
def adminpanel(request):
products=Product.objects.all()
return render(request,'adminpanel/index.html',{'productsall':products})
templates/adminpanel/index.html
{% for item in productsall %}
<tr>
<div class="border1">
<td class="image-cell">
<img src="{{item.show_image.image.url}}"> #this is how i got image url.
</td>
</div>
<td data-label="title">{{item.title}}</td>
<td data-label="category">{{item.category}}</td>
<td data-label="subcategory">{{item.subcategory}}</td>
<td data-label="brand">
{{item.brand}}
</td>
<td data-label="description">
{{item.description}}
</td>
<td class="created">
{{item.created_date}}
</td>
</tr>
<tr>
{% endfor %}
There is so much wrong with your code, I suggest that you do the Django Tutorial first.
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
But if you wan't it working, here is how:
models.py
class Product(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
def first_image(self):
# code to determine which image to show. The First in this case.
return self.images[0]
class ProductImage(models.Model):
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
product = models.ForeignKey(Product, related_name='images')
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html', {'products': queryset})
index.html
{% for product in products %}
<img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}