57040

Django: generate a CSV file and store it into FileField

<h3>Question</h3>

In my Django View file, I need to generate a CSV file from a list of tuples and store the CSV file into the FileField of my model.

class Bill(models.Model): billId = models.IntegerField() bill = models.FileField(upload_to='bills')

I searched on this site, and found some posts such as Django - how to create a file and save it to a model's FileField?, but the solutions can help me.

I need the CSV file to be stored in 'media/bills/' fold, and I hope the CSV file can be deleted together with the Bill object in the database.

I tried the following codes, but it cannot meet my requirements. For each file, it will generate two files 'output.csv' and 'output_xxesss.csv'. At the two files cannot be deleted by calling 'Bill.objects.all().delete()'.

path = join(settings.MEDIA_ROOT, 'bills', 'output.csv') print path f = open(path, 'w+b') f.truncate() csvWriter = csv.writer(f) csvWriter.writerow(('A', 'B', 'C')) for r in rs: print r csvWriter.writerow(convert(r)) bill = Bill() bill.billId = 14 bill.bill.save('output.csv', File(f)) bill.save()

Thanks

I tried the following codes, but it can not delete the file by calling 'Bill.objects.all().delete()'.

bill = Bill() bill.billId = 14 bill.bill.name = 'bills/output.csv' bill.save()
<h3>Answer1:</h3>

Deleting an instance would not delete the associated file. You may consider using signals to be precise pre_delete. You can write a receiver where in you can delete the associated file.

from django.dispatch import receiver from django.db.models.signals import pre_delete @receiver(pre_delete) def func_name(sender, instance, **kwargs): your logic

You can find documentation here.


<h3>Answer2:</h3>

If anyone comes to this post like me and is wondering how to save a csv file directly into a models.FileField i recommend this way:

<pre class="lang-py prettyprint-override">import csv from io import StringIO from django.core.files.base import ContentFile row = ["Name", "Location", "Price"] csv_buffer = StringIO() csv_writer = csv.writer(csv_buffer) csv_writer.writerow(row) csv_file = ContentFile(csv_buffer.getvalue()) bill.bill.save('output.csv', csv_file)

来源:https://stackoverflow.com/questions/42749756/django-generate-a-csv-file-and-store-it-into-filefield

Recommend

  • React/Redux + super agent, first call gets terminated
  • standalone java webservice client
  • How internal tester can download the “Android” pre-released App build?
  • Can we put condition before session timeout in spring?
  • Language Analyzers and Synonyms on same field in elasticsearch
  • Download CSV File by posting JSON data in ASP.NET MVC
  • sys.exc_info()[1] type and format in Python 2.71
  • Calculate SUBTOTAL of a SUMPRODUCT without a column for total
  • Call JQuery function From Controller
  • How to inject String property in a spring bean
  • layer popup with jQuery
  • iTextSharp - SelectPages Method Flattening Form
  • Jsoup (Find Element)
  • How to make binary classication in Spark ML without StringIndexer
  • How to wrap string in span before and after all newlines in PHP?
  • select query in wordpress
  • Xamarin Forms Custom Renderer for Android not displaying
  • Sending PNG attachment via Android GMail app
  • Android MediaCodec appears to buffer H264 frames
  • Gradle refresh removes source folders in build path
  • plot dirac function in matlab
  • ROR + MVC Disable Browser Cache
  • Google TV VideoView playing YouTube rtsp videos
  • .Net core Hosted Services guaranteed to complete
  • opencv deskewing a contour
  • How to define a custom accuracy in Keras to ignore samples with a particular gold label?
  • Create an Office365 mailbox from within C# Web API method
  • Reload Page with Javascript after Database changes
  • Separating definition/instantiation of template classes without 'extern'
  • How to define something in JavaScript [closed]
  • How to write seo friendly url's using htaccess?
  • Django, uWSGI & nginx: Process dies for “no reason”
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • Amazon Elastick BeanStalk error: Failed to create the AWS Elastic Beanstalk application version
  • How to decleare char *const argv[] in swift [duplicate]
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • Grails - How to implement a foreign key relationship not using an id column?
  • Using Service Component Runtime
  • Jersey serializes character value to ASCII equivalent numeric string
  • media foundation H264 decoder not working properly