I'm calculating the min and max values so I can display the spread of RRPs for a car model. Here I just have the min value, which is being calculated correctly but it will not display to the index file using the guidance I got from various examples/sites.
Greatly appreciatte any help.
Models.py
class MotorMakes(models.Model):
MotorMakeName = models.CharField(max_length=50, unique=True, default=False)
def __str__(self):
return self.MotorMakeName or ''
def __unicode__(self):
return u'%s' % (self.MotorMakeName) or ''
class MotorModelsV2(models.Model):
MotorMakeName = models.CharField(max_length=50, default=False,)
MotorModelName = models.CharField(max_length=50, default=False,)
Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False)
Mlid = models.IntegerField(default=False, unique=True)
MotorImage = models.ImageField(upload_to='Car_Pics', default=False,blank=True)
def __str__(self):
return self.MotorModelName or ''
def __unicode__(self):
return u'%s' % (self.MotorModelName) or ''
class Meta:
ordering = ('MotorMakeName',)
class MotorDetail(models.Model):
MotorMakeName = models.CharField(max_length=50, default=False,)
MotorModelName = models.CharField(max_length=50, default=False,)
title = models.CharField(max_length=100, default=False,)
fuel = models.CharField(max_length=25, default=False,)
body = models.CharField(max_length=25, default=False,)
engine = models.CharField(max_length=5, default=False,)
#Mkid = models.CharField(max_length=5, default=False,)
#Mlid = models.CharField(max_length=5, default=False,)
Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False, null=True)
Mlid = models.ForeignKey(MotorModelsV2,on_delete=models.CASCADE, default=False, null=True)
RRP = models.DecimalField(max_digits=10, decimal_places=2, default ='0' )
MotorImage = models.ImageField(upload_to='Car_Pics', default=False,blank=True)
def __str__(self):
#return self.title or ''
return '%s %s %s' % (self.MotorMakeName,self.MotorModelName, self.title,) or ''
def __unicode__(self):
return u'%s' % (self.title) or ''
class Meta:
ordering = ('MotorMakeName',)
View.py
def SearchInventory(request):
if request.method=='GET':
inputvalue = request.GET['modelselection']
print(inputvalue)
DisplayInventory = GarageInventory.objects.all().filter(ListModel=inputvalue) #join to MotorDetails with Title and Body to get the image, as well as the RRP, then just output this to html
DisplayImage = MotorModelsV2.objects.all().filter(MotorModelName=inputvalue)
DisplayRRP=MotorDetail.objects.all().filter(MotorModelName=inputvalue).aggregate(Min('RRP'))
else:
DisplayInventory = GarageInventory.objects.all()
return render(request, 'search_results.html', {'GarageInventoryView':DisplayInventory,'ImageView':DisplayImage, 'RRPView': DisplayRRP })
Index.html
{% for inv in GarageInventoryView %}
<tbody class = "table table-hover">
<tr align="center">
<td align="center">{{inv.GarageID}}</td>
<td align="center">{{inv.ListModel}}</td>
<td align="center">{{inv.ListMake}}</td>
<td align="center">{{inv.Title}}</td>
<td align="center">{{inv.Year}}</td>
<td align="center">{{inv.BodyType}}</td>
<td align="center">{{inv.GaragePrice}}</td>
<td align="center">Base RRP is {{ RRP__min}}</td>
{% for imgs in ImageView %}
<td> <img src="{{ imgs.MotorImage.url }}" alt="{{inv.ListModel}} image",height="75", width="120" /></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
In your views.py, you defined the key for the aggregate result, inside your context dictionary, as RRPView:
return render(request, 'search_results.html', {'GarageInventoryView':DisplayInventory,'ImageView':DisplayImage, 'RRPView': DisplayRRP })
But when you are attempting to access the aggregate value in your template, you are trying to access the default name for the aggregate value (RRP__min), instead of the key stored in your context:
<td align="center">Base RRP is {{ RRP__min}}</td>
Change that line to:
<td align="center">Base RRP is {{ RRPView.RRP__min }}</td>
Your context dictionary contains a key called RRPView; the value of RRPView is the dictionary returned by the Aggregate function. Inside that dictionary is the key RRP__min, which holds as a value the result of your aggregate.
Related
I have to models Customers and Purchase_order. I am taking customer as a foreign key in purchase invoice and fetching data..
My data is like this:
{'id': 5, 'purchase_number': 'TES-PO-1', 'purchase_date': datetime.date(2022, 9, 1), 'customer_id_id': 1, 'special_instructions': '', 'total': '70', 'discount': 2.578125, 'round_off': '77.5', 'grand_total': '78', 'user_id': 1, 'remarks': '', 'company_id': 1}
{'id': 6, 'purchase_number': 'TES-PO-2', 'purchase_date': datetime.date(2022, 9, 6), 'customer_id_id': 2, 'special_instructions': '', 'total': '24', 'discount': 0.75, 'round_off': '28.5', 'grand_total': '29', 'user_id': 1, 'remarks': '', 'company_id': 1}
Action
here I am getting customer id as 1,2,3 its pk value but I wish to call its customer_company there.. how can I access them by its id on frontend?
want to show name instead of ID
views.py
def get_sales_invoices(request):
company_label= Company_Setup.objects.get(id=request.session['company_id'])
invoices=Sales_Invoice.objects.filter(company=company_label).all().values()
customer_data=[]
for c in invoices:
cust_id=c['customer_id_id']
customers_details= Customer.objects.filter(id=cust_id).all().values()
customer_data.append(customers_details)
return render(request,"sales/list_sales_invoice.html",{'invoices':invoices, 'customer_data':customer_data})
customer/models.py
class Customer(models.Model):
customer_id = models.CharField(unique=True,max_length=50)
customer_company = models.CharField(max_length=50,default=True)
title = models.CharField(max_length=100, choices=TITLE_CHOICES, default="NA")
first_name = models.CharField(max_length=50, default=True)
middle_name = models.CharField(max_length=50, default=True)
surname = models.CharField(max_length=50, default=True)
company= models.ForeignKey(Company_Setup,on_delete=models.CASCADE,default=True)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pin = models.CharField(max_length=50)
country = models.CharField(max_length=50)
country_code=models.CharField(max_length=50)
customer_address = models.CharField(max_length=50, default=True)
contact_person_name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
email = models.CharField(max_length=50)
website= models.CharField(max_length=50, default="NA")
GST = models.CharField(max_length=50)
bill_to = models.CharField(max_length=50)
ship_to = models.CharField(max_length=50)
payment_method = models.CharField(max_length=100, choices=PAYMENT_CHOICES, default="Normal")
terms = models.CharField(max_length=100, choices=TERMS_CHOICES, default="NA")
deffered= models.CharField(max_length=100, choices=DEFERRED_CHOICES, default="NA")
def __str__(self):
return self.customer_company
purchase/model
class Purchase_Order(models.Model):
purchase_number=models.CharField(unique=True,max_length=50,default=True)
purchase_date=models.DateField()
supplier=models.ForeignKey(Supplier,on_delete=models.CASCADE) #Foreign key
special_instructions=models.CharField(max_length=50)
total=models.CharField(max_length=50)
discount=models.FloatField(max_length=50,default=0)
round_off=models.CharField(max_length=50)
grand_total=models.CharField(max_length=50)
user =models.ForeignKey(User,on_delete=models.CASCADE)
remarks=models.CharField(max_length=50)
company=models.ForeignKey(Company_Setup,on_delete=models.CASCADE,default=True)
you can get the customer object customer = Customer.objects.get(pk=customer_ID) then access the name field of Customer model by name = customer.name
==== I have two models In AddmitatonModel has foreign key of StudentModel ====
class StudentModel(models.Model):
name = models.CharField(max_length=255)
roll = models.PositiveIntegerField()
email = models.EmailField()
city = models.CharField(max_length=255)
def __str__(self):
return self.name
class AddmissionModel(models.Model):
student = models.ForeignKey(StudentModel,on_delete=models.CASCADE)
status = models.BooleanField(default=False)
def __str__(self):
return str(self.student.name)
======== in view.py =========
def DemoView(request):
all_students = AddmissionModel.objects.all()
context = {'all_students':all_students}
return render(request,'demo.html',context)
====== in html file itrated all student detail using foreigenkey ======
<table>
<thead>
<tr style="border-bottom: 1px solid;">
<th>No.</th>
<th>Student name</th>
<th>Student Roll</th>
<th>Student Email</th>
<th>Student City</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for i in all_students %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.student.name}}</td>
<td>{{i.student.roll}}</td>
<td>{{i.student.email}}</td>
<td>{{i.student.city}}</td>
<td>{{i.status}}</td>
</tr>
{% endfor %}
</tbody>
</table>
======== Webpage output =============
This worked on me
views.py
#login_required(login_url='/login')
def get_sales_invoices(request):
company_label= Company_Setup.objects.get(id=request.session['company_id'])
invoices=Sales_Invoice.objects.filter(company=company_label).all()
invoice_list = [[i.customer_id.customer_company, i.invoice_number, i.invoice_date, i.grand_total,i.id] for i in invoices]
response = invoice_list
return render(request,"sales/list_sales_invoice.html",{'invoices':invoices, 'customer_data':response})
html
<tbody id="rows">
{% if customer_data %}
{% for i in customer_data %}
<tr>
<td><a class='bx bxs-edit' style="text-decoration:None"
href="/sales/update/{{i.4}}"></a>
<a class="fas fa-eye" href="/sales/sales-invoice-pdf/{{i.4}}">
</td>
<th>{{i.2}}</th>
<th>{{i.1}}</th>
<th>{{i.0}}</th>
<th>{{i.3}}</th>
</tr>
{% endfor %}
{% endif %}
</tbody>
I tried to look up the order class and get the last 5 orders with their customer and items. But got the following exception:
*Exception Type: ValueError
Exception Value:
Negative indexing is not supported.*
Here are the models:
class Customer(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Order(models.Model):
placed_at = models.DateTimeField(auto_now_add=True)
customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.PROTECT)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
And here is the view class:
def last_5_orders(request):
orders = Order.objects.select_related('customer').prefetch_related('orderitem_set__product').order_by('placed_at')[-5:]
return render(request, 'last_5_orders.html', {'orders': orders})
And finally in last_5_orders.html file I have:
{% for order in orders %}
<h1>
{{ order.id }} : {{ order.custumer.first_name }} {{ order.custumer.last_name }} PURCHASED {{order.orderitem_set.product}}
</h1>
{% endfor %}
Any ideas about resolving this issue?
Trying to fetch a function from a table that is supposed to be there, but cannot get the value. Trying to get the amount of task that is completed.
models.py
class Task(models.Model):
title = models.CharField(max_length=55, null=True, blank=True)
slug = models.SlugField(max_length=500, unique=True, blank=True)
task_completed = models.BooleanField(default=False)
description = models.TextField(default="Task description")
start_date = models.DateTimeField()
due_date = models.DateTimeField()
checklist = models.ManyToManyField(Checklist, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Task, self).save(*args, **kwargs)
def get_url(self):
return reverse('checklists', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
#property
def num_task_completed(self):
return self.task_completed.count()
class Project(models.Model):
project_manager = models.ForeignKey(Profile, on_delete=CASCADE)
title = models.CharField(max_length=55, null=True, blank=True)
developers = models.ManyToManyField(Profile, related_name='projects')
slug = models.SlugField(max_length=500, unique=True, blank=True)
description = models.TextField(default="Project description")
date = models.DateTimeField(auto_now_add=True)
start_date = models.DateTimeField()
due_date = models.DateTimeField()
tasks = models.ManyToManyField(Task, blank=True)
teams = models.ManyToManyField(Team, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def get_url(self):
return reverse('project_detail', kwargs={
'slug':self.slug
})
def __str__(self):
return self.title
#property
def num_task(self):
return self.tasks.count()
Then in the html is just loop through all projects
{% for projects in projects.all %}
<span class="text-small"> {{ projects.tasks.num_task_completed }} /{{ projects.num_task }}</span>
I manage to get the amount of tasks, but not the amount completed.
Use self.tasks.filter(task_completed = True).count() to get the number of completed tasks in a project.
I have the following two models:
class Company(db.Model):
__tablename__ = "company"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), index=True, unique=True, nullable=False)
comments = db.relationship("Comment", backref="comment", lazy=True)
class Comment(db.Model):
__tablename__ = "comment"
id = db.Column(db.Integer, primary_key=True)
company_id = db.Column(db.Integer, db.ForeignKey("company.id"), nullable=False)
body = db.Column(db.Text)
created_datetime = db.Column(
db.TIMESTAMP(timezone=True), default=datetime.datetime.now
)
And the following Jinja2 template:
{% for comment in company.comments %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
I'd like to order the comments by created_datetime desc.
Can I do that in the Jinja2 template?
In Jinja2:
Ascending
{% for comment in company.comments|sort(attribute='created_datetime') %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
Descending
{% for comment in company.comments|sort(attribute='created_datetime', reverse = True) %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
Or do the sort in Python prior to passing company to the template:
#app.route('/')
def index():
# e.g company 10
company = Company.query.join(Company.comments).filter(Company.id == 10).order_by(Comment.created_datetime.desc()).first_or_404()
render_template('index.html', company=company)
I use IntegerField in Answer form for getting id of question page. But IntegerField doesn't get the id page, that get title of this page. I thought it because primary key is title, but not, I tried to set id = models.AutoField(primary_key=True) in Question and Answer models, but the situation is the same. This iss my form class:
class AddAnswerForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
question = forms.IntegerField()
def clean_question(self):
question_id = self.cleaned_data['question']
try:
question = Question.objects.get(id=question_id)
except Question.DoesNotExist:
question = None
return question
def clean(self):
pass
def save(self):
answer = Answer(**self.cleaned_data)
answer.save()
return answer
That's my models:
class Question(models.Model):
title = models.CharField(default='', max_length=255)
text = models.TextField(default='')
added_at = models.DateTimeField(blank=True, auto_now_add=True)
rating = models.IntegerField(default=0)
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='question_user')
likes = models.ManyToManyField(User, related_name='question_like_user')
def __str__(self):
return self.title
def get_url(self):
return '/question/{}/'.format(self.id)
class Answer(models.Model):
text = models.TextField(default='')
added_at = models.DateField(blank=True, auto_now_add=True)
question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True, related_name='answer_question')
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='answer_user')
def __str__(self):
return self.text
And that's my view:
def question(request, pk):
try:
q = Question.objects.get(id=pk)
except Question.DoesNotExist:
raise Http404
a = Answer.objects.all()
u = User.objects.all()
if request.method == 'POST':
form = AddAnswerForm(request.POST)
if form.is_valid():
_ = form.save()
url = q.get_url()
return HttpResponseRedirect(url)
else:
form = AddAnswerForm(initial={
'question': q,
'answer': a,
'user': u,
})
return render(request, 'question.html',
{
'form': form,
'question': q,
'answer': a,
'user': u,
})
Thank you.