Search code examples
pythondjangoxlrd

Django Model method variable put into template


I have a model and I want to get the method variable "row_count and column" count to put the value into the templates.

class Data(models.Model):
    """ Model of Data"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    document = models.FileField(upload_to='documents/%Y/%m/%d')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    amount = models.DecimalField(default=0, max_digits=6, decimal_places=2,
                                 blank=True, null=True)

    def calculate_amount(self):
        # wb = xlrd.open_workbook('media/' + self.document.name)
        wb = xlrd.open_workbook(os.path.join(settings.MEDIA_ROOT,
                                             self.document.name))
        worksheet = wb.sheet_by_index(0)

        # Show this value into templates
        row_count = worksheet.nrows
        column_count = worksheet.ncols



Solution

  • You could use something like the following snippet, your model will now have 2 new attributes, row_count and columns_count, that can be called within your template and each of them will call calculate_amount to retrieve their values.

    The if I added on calculate_amount prevents multiple calls to it to avoid multiple file reads and perhaps slowing your application.

    class Data(models.Model):
        """ Model of Data"""
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        document = models.FileField(upload_to='documents/%Y/%m/%d')
        uploaded_at = models.DateTimeField(auto_now_add=True)
        amount = models.DecimalField(default=0, max_digits=6, decimal_places=2,
                                     blank=True, null=True)
    
        def calculate_amount(self):
            if hasattr(self, '_row_count') or hasattr(self, '_column_count'):
                return
            # wb = xlrd.open_workbook('media/' + self.document.name)
            wb = xlrd.open_workbook(os.path.join(settings.MEDIA_ROOT,
                                                 self.document.name))
            worksheet = wb.sheet_by_index(0)
    
            # Show this value into templates
            self.row_count = worksheet.nrows
            self.column_count = worksheet.ncols
    
        @property
        def row_count(self):
            self.calculate_amount()
            return self._row_count
    
        @row_count.setter
        def row_count(self, value):
            self._row_count = value
    
        @property
        def column_count(self):
            self.calculate_amount()
            return self._column_count
    
        @column_count.setter
        def column_count(self, value):
            self._column_count = value
    

    Updated with property setters.