How to pass file's content as CharField in django model?

Viewed 93

I have a model for icon, which looks like this:

class Icon(models.Model):
    name = models.CharField(max_length=50)
    icon = models.FileField(upload_to='icons/', blank=True, null=True)
    inline_svg = models.CharField(max_length=1000, blank=True)

Most of files are .svg and I want to pass into inline_svg content of corresponding file to use inline svg on front-end. How can i do that? Or maybe there is any better variants to do what I want?

Also had an idea of something like this:

class Icon(models.Model):
    def svg(self):
        f = open(self.icon.url)
        return f.read()
    name = models.CharField(max_length=50)
    icon = models.FileField(upload_to='icons/', blank=True, null=True)
    inline_svg = models.CharField(max_length=1000, default=svg())
1 Answers

Let's see if I understood your question correctly. Users upload files, and when the file is svg, you want to store it in inline_svg?

class Icon(models.Model):
    name = models.CharField(max_length=50)
    icon = models.FileField(upload_to='icons/', blank=True, null=True)
    inline_svg = models.CharField(max_length=1000, default='')

    def save(self, *args, **kwargs):
        if self.icon.name.endswith('.svg'):
            self.inline_svg = self.icon.read()
        super().save(*args, **kwargs)
Related