I have a django table with a column that has decimal points upto 7 points. The column is called error. Can anyone help me truncate the data to only two decimal points or maybe round the number?
model:
class Course (models.Model):
null_value = 0
department = models.CharField(max_length=200)
course = models.CharField(max_length=200)
semester = models.CharField(max_length=200)
actual = models.FloatField (default=0)
prediction = models.FloatField(default=0)
error = models.FloatField(default=0)
table
class NameTable(tables.Table):
# actions = tables.Column(orderable=False)
# selection = tables.CheckBoxColumn(accessors="pk", orderable = False)
# table = n_object.filter(course=course_selected).order_by('id').all()
table=tables.Table
# actual1 = table.values_list('actual')
error = tables.Column(verbose_name='ERROR (%)')
class Meta:
model = Course
fields = ("semester","actual","prediction","error")
order_by_field = True
whats in the view (i modified it to what you guys need):
def report_table1(request):
n_object = Department.objects.all()
table = n_object.filter(department=department_selected).order_by('id').all()
t_data = NameTable(table)
RequestConfig(request).configure(t_data)
return render(request, 'table.html', {"table_course": t_data})
html file
{% block content %}
{% load render_table from django_tables2 %}
<div style="text-align: center;">
<!--<h2>Prediction for all Courses</h2>-->
<!--<table style="width: 100%;" "text-align:center;">-->
{% render_table table_course%}
<!--</table>-->
{% endblock %}
what should I do? I would prefer to round the number in the error column
Another solution you can use:
class NameTable(tables.Table):
def render_error(self, **kwargs):
return round(kwargs['value'], 2)
# or you can return like markdesign's answer :)
#return u"%.2f" % (kwargs['value'])
class Meta:
model = Course
fields = ("semester","actual","prediction","error")
order_by_field = True
Here is a simple solution, you can round your data using a simple trick. You should create a property inside your model that defines a rounded value for your error record. Let's see the code (it should work but I can't test it right now):
Model:
class Course (models.Model):
null_value = 0
department = models.CharField(max_length=200)
course = models.CharField(max_length=200)
semester = models.CharField(max_length=200)
actual = models.FloatField (default=0)
prediction = models.FloatField(default=0)
error = models.FloatField(default=0)
#property
def roundedError(self):
return u"%.2f" % (self.error)
# or you can return like ruddra's answer ;)
# return round(self.error, 2)
Table:
class NameTable(tables.Table):
...
roundedError = tables.Column()
Related
views.py
def contest(request):
context = {}
all_contest = Contest.objects.all()
context["contest"] = all_contest
return render(request,"contest.html",context)
def contest_candidates(request,id):
context = {}
all_candidates_ = Contest_Candidates.objects.filter(contest_id = id)
high_like = 0
winner_ = ""
for i in all_candidates_:
if i.likes_count > high_like:
high_like = high_like + i.likes_count
winner_ = i.owner.name
context["cadidates"] = all_candidates_
return render(request,"view_contest_candidates.html",context)
urls.py
path("contest",views.contest, name="contest"),
path("candidates/<id>",views.view_contest_candidates, name="candidates"),
models.py
class Contest(models.Model):
title = models.CharField(max_length=50)
class Contest_Candidates(models.Model):
image = models.FileField( upload_to="contest_candidates/",)
owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
contest = models.ForeignKey(Contest, on_delete=models.CASCADE,related_name='candidates')
#property
def likes_count(self):
return self.likes.all().count()
class CandidateLikes(models.Model):
like = models.CharField(max_length=10)
user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='candidate_likes')
contest_candidates = models.ForeignKey(Contest_Candidates, on_delete=models.CASCADE, related_name='likes')
how to pass the winner variable in to contest function ? i need to show that in contest.html
if it's not possible, which is the best method . want to show every contest winner in contest.html
As far as I understand - winner variable is calculated in your second function.
Nothing prevents calculating it in contest as well:
models.py
class Contest(models.Model):
title = models.CharField(max_length=50)
#property
def winner(self):
high_like = 0
all_candidates_ = Contest_Candidates.objects.filter(contest=self)
winner = None
for c in all_candidates_:
if c.likes_count > high_like:
winner = c.owner
return winner
views.py
def contest(request):
context = {"contests": Contest.objects.all()}
return render(request,"contest.html",context)
def contest_candidates(request,id):
contest = Contest.objects.get(id=id)
context = {
"contest": contest,
"candidates": Contest_Candidates.objects.filter(contest=contest)
}
return render(request,"view_contest_candidates.html",context)
contest.html
{% for c in contests %}
{{ c.title }}
{{ c.winner.name }}
{% endfor %}
When I enter my user profile page, I want it to see the total number of orders until today. i tried aggregate and annonate but it's not work. I hope so i use filter method but i don't know how to do it.
Orders count = adet in model
I added ""if siparis.bayi_id == user.id"" so that the user entering can take action on his orders.
Temp Html
{% for siparis in siparis %}
{% if siparis.bayi_id == user.id %}
<strong>{{ a }}</strong><br><small>Siparişler Toplamı</small>
{% endif %}
{% endfor %}
Model Siparis means order
class Siparis(models.Model):
bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"})
urun = models.ForeignKey(Urun, on_delete=models.CASCADE)
adet = models.IntegerField()
tarih = models.DateTimeField()
status = models.BooleanField()
#property
def miktar(self):
return (self.adet * self.urun.fiyat)
#property
def fiyat(self):
return self.urun.fiyat
class Meta:
verbose_name = 'Bayi Sipariş'
verbose_name_plural = 'Bayi Siparişleri'
views
def bayi_bayidetay(request):
siparis = Siparis.objects.all()
urunler = Urun.objects.all()
bayiler = bayi_bilgi.objects.all()
a = Siparis.objects.aggregate(Sum("adet"))
return render(request,'bayi/bayi_detay.html',{'bayiler':bayiler,'siparis':siparis,'urunler':urunler, 'a': a})
Thank you
You can try add filter after a, like this:
a = Siparis.objects.filter(bayi=request.user).aggregate(Sum("adet"))
**I want get all orders of customer whose id = 3 **
----------------------------------------------------------------
class customer(models.Model):
name = models.CharField(max_length=200,null= True)
phone = models.CharField(max_length=200,null= True)
email = models.CharField(max_length=200,null= True)
date_created = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return self.name
class order(models.Model):
STATUS = (
('pending','pending'),
('out for delivery','out for delivery'),
('deliveried','deliveried')
)
date_created = models.DateTimeField(auto_now_add=True,null=True)
status = models.CharField(max_length = 200 , null=True,choices=STATUS)
customer= models.ForeignKey(customer,null=True,on_delete=models.SET_NULL)
product = models.ForeignKey(product,null=True,on_delete=models.SET_NULL)
There are two possible ways to do it.
One way is from order objects:
order.objects.filter(customer__id=3)
Second from customer objects:
customer.objects.get(id=3).order_set.all()
its actually quite simple.
just do the following
order.objects.filter(customer_id=3)
you can use the filter method provided by Django model class
This method returns all the orders in a query-set object.
so one more question might raise is where we should actually use this method?
You can actually do this in your views.py
Example:
urls.py
path('my_view/<int:id>',views.my_order,name="my_order")
views.py
def my_order(request,id):
my_orders = order.objects.filter(customer_id=3) #this will return a query set
return render(request,'index.html',{'my_orders':my_orders})
index.html
<body>
{% for o in my_orders %}
{{o}}
{% endfor %}
</body>
I have tried like this. But it is returning the only one combined value.
class Employees(models.Model):
nameininitials = models.TextField(null=True)
nameinuse = models.TextField(null=True)
employeeno = models.TextField(null=True)
departmentname = models.TextField(null=True)
def __str__(self):
return '{} {}'.format(self.nameinuse, self.employeeno)
class Region(models.Model):
regionname = models.TextField(null=True)
regionalincharge = models.ForeignKey(Employees, on_delete=models.CASCADE,null = True)
When I use datalist = Region.objects.all() , I want all fields from Employees table in different variables or array to use in template.
# If this is your query in your views function or class
datalist = Region.objects.all()
# then you can access 'Employees' data in your template by using '.' operator.
For example
views.py
def view_function(request):
datalist = Region.objects.all()
return render(request, 'template_name.html', { 'datalist': datalist })
template_name.html
{% for data in datalist %}
<p>{{data.regionalincharge.nameininitials}}</p>
<p>{{data.regionalincharge.nameinuse}}</p>
<p>{{data.regionalincharge.employeeno}}</p>
<p>{{data.regionalincharge.departmentname}}</p>
<hr />
{% endfor %}
I want to be able to produce a dropdown menu in my template with a unique list of subjects.
Subjects are populated inside of admin rather than hard coding them in SUBJECT_CHOICES.
A course can have many subjects or only 1 subject. For example:
Course Title = Django
Subject = Technology
Course Title = Python
Subject = Technology
Course Title = Accounting
Subject = Business
Course Title = E-commerce
Subject(s) = Technology, Business
CourseListView corresponds to the course_list.html template.
models.py:
class Subject(models.Model):
SUBJECT_CHOICES = ()
name = models.CharField(max_length=20,choices=SUBJECT_CHOICES, unique=True)
def __str__(self):
return self.name
class Course(models.Model):
SKILL_LEVEL_CHOICES = (
('Beginner', 'Beginner'),
('Intermediate', 'Intermediate'),
('Advanced', 'Advanced'),
)
slug = models.SlugField()
title = models.CharField(max_length=120)
description = models.TextField()
allowed_memberships = models.ManyToManyField(Membership)
created_at = models.DateTimeField(auto_now_add=True)
subjects = models.ManyToManyField(Subject)
skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True)
visited_times = models.IntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('courses:detail', kwargs={'slug': self.slug})
#property
def lessons(self):
return self.lesson_set.all().order_by('position')
views.py:
class CourseListView(ListView):
model = Course
def get_queryset(self):
qs = super().get_queryset()
title_contains_query = self.request.GET.get('title_contains')
view_count_min = self.request.GET.get('view_count_min')
view_count_max = self.request.GET.get('view_count_max')
date_min = self.request.GET.get('date_min')
date_max = self.request.GET.get('date_max')
skill_level_query = self.request.GET.get('skill_level')
if title_contains_query:
qs = qs.filter(title__icontains=title_contains_query)
if view_count_min:
qs = qs.filter(visited_times__gte=view_count_min)
if view_count_max:
qs = qs.filter(visited_times__lte=view_count_max)
if date_min:
qs = qs.filter(created_at__gte=date_min)
if date_max:
qs = qs.filter(created_at__lte=date_max)
if skill_level_query:
qs = qs.filter(skill_level=skill_level_query)
return qs
Desired Output:
I tried writing a for loop in my template that does return the subjects successfully but they are not unique or showing only once.
{% for item in object_list %}
<h2>{{ item.subjects.all}}</h2>
<ul>
{% for sub in item.subjects.all %}
<li>{{ sub.name }}</li>
{% endfor %}
</ul>
{% endfor %}
Result:
<QuerySet [<Subject: Business>]>
Business
<QuerySet [<Subject: Technology>]>
Technology
<QuerySet [<Subject: Technology>]>
Technology
<QuerySet [<Subject: Business>]>
Business
I would prefer to do it with a for loop that produces unique results, but maybe it can be done with django-select2 or use a form with model select or multiple model select? Can someone provide some code for either the loop or one of these methods?
I would appreciate any help with this.
I see two solutions here:
The first one if to simply get all the entered values in the Subject model but you couldn't use all the filters you are using in your view, only the one about the title.
To do so, just use:
title_contains_query = self.request.GET.get('title_contains')
if title_contains_query:
subjects = [title for title in Subject.objects.filter(title__icontains=title_contains_query)]
The other option is to use the distinct() method on your QuerySet which filters and remove the duplicate entries in it. Use it like this: qs = qs.distinct()
Hope it helps!