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
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()
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.