Say I've stored a text file in FileField. Now I want to display its content on the webpage. I read the django template document but didn't find a way to do this.
Of course I can do content = f.read()
in my views and pass content
to the template. Is there a better way? Thank you!
better way
means I could get the job done by passing MyModel.objects.all()
to template.I can't read
a file in template, but there should be some kind of hacks for this.
edit
I've tried:
def display_html(self):
content = self.html_file.read()
print(content)
return content
but nothing displayed...
final edit
It's very strange that the following code works
class MyModel(models.Model):
name = models.CharField()
text = models.FileField()
def display_text_file(self):
fp = open(self.text.path)
return fp.read().replace('\n', '<br>')
However what I regard as equivalent doesn't work:
class MyModel(models.Model):
name = models.CharField()
text = models.FileField()
def display_text_file(self):
return self.text.read().replace('\n', '<br>')
# neither do self.text.read().decode().replace('\n', '<br>')
I really want to know the reason.