0

I need to read the contents of a csv file and save into a model.

# MODEL
class FileUpload(models.Model):
    datafile = models.FileField(upload_to=file_path_name)


# SIGNAL TO READ THE FILEUPLOAD INSTANCE
@receiver(post_save, sender=FileUpload)
def fileupload_post_save(sender, instance, *args, **kwargs):
    with open(instance.datafile, 'rb') as f:
        reader = csv.DictReader(f, delimiter='\t')
        for row in reader:
            print row

The serializer file.

# SERIALIZER
class FileUploadSerializer(serializers.ModelSerializer):

    class Meta:
    model = FileUpload

When I upload the file, appears this error.

Got a `TypeError` when calling `FileUpload.objects.create()`. 
This may be because you have a writable field on the serializer class that is not a valid argument to `FileUpload.objects.create()`. You may need to make the field read-only, or override the FileUploadSerializer.create() method to handle this correctly.
Original exception text was: coercing to Unicode: need string or buffer, FieldFile found.

The open() method should not open an instance of this FileField file?

Does anyone have a better idea for parsing this file? I upload the file and then read or could read before saving? Thanks!!

2 Answers 2

2

This is the solution. It's necessary to pass the request directly to DictReader:

if serializer.is_valid():
    data = self.request.data.get('datafile')
    reader = csv.DictReader(data, delimiter='\t')
    for row in reader:
        print row['customer']
Sign up to request clarification or add additional context in comments.

Comments

0

FieldFile is the data stored on a FileField. If you're looking to open it using the Python open method, you should instead be calling FieldFile.open(). The error is coming from within your post-save signal handler, because open expects the name of a file and you are passing in a FieldFile.

1 Comment

Thanks! The solution is to pass the file on request directly to the DictReader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.