Django FileField编码 [英] Django FileField encoding
问题描述
我有一个django模型,如下所示:
I have a django model as follows:
class ExportFile(BaseExportFile):
created_timestamp = models.DateTimeField(auto_now=True, editable=False)
data = models.FileField(upload_to='exports')
和一个渲染模板以创建csv文件的视图函数:
and a view function that renders a template to create a csv file:
def create_csv(request):
context = Context({'data': MyModel.objects.all()})
rendered = render_to_string('mytemplate.html', context)
# create tradefile and save
cf = ContentFile(rendered)
tf = ExportFile()
tf.data.save('myfile.csv', cf)
tf.save()
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'myfile.csv'
response.write(rendered)
return response
该视图不仅将csv数据保存到FileField,而且还将其返回给浏览器.我的问题是浏览器文件运行正常,但是保存在模型上的文件大小是原来的两倍,当我使用差异程序时,我可以看到额外的隐藏字符.我认为这一定与mime类型和django自动保存utf8有关,但我只是想不通!
The view not only saves the csv data to a FileField but it also returns it to the browser. The problem I have is the browser file works perfectly, but the file saved on the model is twice the size and when I use a diff program I can see extra hidden characters. I think it must be to do with the mime type vs django auto saving utf8 but I just can't figure it out!
推荐答案
解决了问题!
ContentFile是cStringIO.StringIO的子类-处理ASCII编码的文件.因此,由于django中的所有内容默认均为UTF8,因此该字符串需要编码为ASCII
The ContentFile is a subclass of cStringIO.StringIO - which deals with ASCII encoded files. The string therefore needs to be encoded as ASCII as everything in django is UTF8 by default
cf = ContentFile(rendered.encode('ascii'))
这篇关于Django FileField编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!