可以定義爲類有FileField
,如果你想要做的FileField
超過read
方法做,例如用於display_text_file
的方法,然後在模板調用它。
型號:
class MyModel(models.Model):
name = models.CharField(max_length=100)
text = models.FileField(max_length=100, upload_to='.')
def display_text_file(self):
with open(self.text.path) as fp:
return fp.read().replace('\n', '<br>')
瀏覽:
def show_files(request):
objects = MyModel.objects.all()
return render_to_response('show_files.html', {'objects': objects},
context_instance=RequestContext(request))
模板:
{% for obj in objects %}
<p>
file name: {{obj.name}} <br>
file content: {{obj.display_text_file}}
</p>
{% endfor %}
爲了打開文件的方式,在display_text_file
,所有這些方面的工作對我來說:
def display_text_file(self):
with open(self.text.path) as fp:
return fp.read().replace('\n', '<br>')
def display_text_file(self):
self.text.open() # reset the pointer of file, needs if you need to read file more than once, in a request.
return self.text.read().replace('\n', '<br>')
def display_text_file(self):
self.text.open() # reset the pointer of file, needs if you need to read file more than once, in a request.
return self.text.file.read().replace('\n', '<br>')
的self.text
類型是django.db.models.fields.files.FieldFile
和具有以下方法:
['DEFAULT_CHUNK_SIZE', 'chunks', 'close', 'closed', 'delete', 'encoding', 'field', 'file',
'fileno', 'flush', 'instance', 'isatty', 'multiple_chunks', 'name', 'newlines', 'open', 'path',
'read', 'readinto', 'readline', 'readlines', 'save', 'seek', 'size', 'softspace', 'storage', 'tell',
'truncate', 'url', 'write', 'writelines', 'xreadlines']
和self.text.file
類型是django.core.files.base.File
,並具有以下的方法:
['DEFAULT_CHUNK_SIZE', 'chunks', 'close', 'closed', 'encoding', 'file',
'fileno', 'flush', 'isatty', 'mode', 'multiple_chunks', 'name', 'newlines', 'open',
'read', 'readinto', 'readline', 'readlines', 'seek', 'size', 'softspace', 'tell',
'truncate', 'write', 'writelines', 'xreadlines']
而且兩者具有read
方法。
您可以創建自己的小部件並覆蓋render()方法,但是您也必須閱讀該文件。見https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.render – gawel
@gawel謝謝,我現在要讀它 – laike9m
@gawel這不是我所需要的假設... – laike9m