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')
and a view function that renders a template to create a csv file:
def create_csv(request):
context = Co开发者_Python百科ntext({'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
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!
Solved the problem!
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'))
精彩评论