Django test FileField using test fixtures

Django provides a great way to write tests on FileFields without mucking about in the real filesystem – use a SimpleUploadedFile. from django.core.files.uploadedfile import SimpleUploadedFile my_model.file_field = SimpleUploadedFile(‘best_file_eva.txt’, b’these are the contents of the txt file’) It’s one of django’s magical features-that-don’t-show-up-in-the-docs :). However it is referred to here.

copy file from one model to another

Inspired by Gerard’s solution I came up with the following code: from django.core.files.base import ContentFile #… class Example(models.Model): file = models.FileField() def duplicate(self): “”” Duplicating this object including copying the file “”” new_example = Example() new_file = ContentFile(self.file.read()) new_file.name = self.file.name new_example.file = new_file new_example.save() This will actually go as far as renaming the file … Read more

Django REST Framework and FileField absolute url

Try SerializerMethodField Example (untested): class MySerializer(serializers.ModelSerializer): thumbnail_url = serializers.SerializerMethodField(‘get_thumbnail_url’) def get_thumbnail_url(self, obj): return self.context[‘request’].build_absolute_uri(obj.thumbnail_url) The request must available to the serializer, so it can build the full absolute URL for you. One way is to explicitly pass it in when the serializer is created, similar to this: serializer = MySerializer(account, context={‘request’: request})

How to assign a local file to the FileField in Django?

Django uses it’s own file type (with a sightly enhanced functionality). Anyway Django’s file type works like a decorator, so you can simply wrap it around existing file objects to meet the needs of the Django API. from django.core.files import File local_file = open(‘mytest.pdf’) djangofile = File(local_file) pdfImage.myfile.save(‘new’, djangofile) local_file.close() You can of course decorate … Read more

Save base64 image in django file field

import base64 from django.core.files.base import ContentFile format, imgstr = data.split(‘;base64,’) ext = format.split(“https://stackoverflow.com/”)[-1] data = ContentFile(base64.b64decode(imgstr), name=”temp.” + ext) # You can save this as file instance. Use this code snippet to decode the base64 string.

What is the clean way to unittest FileField in django?

Django provides a great way to do this – use a SimpleUploadedFile or a TemporaryUploadedFile. SimpleUploadedFile is generally the simpler option if all you need to store is some sentinel data: from django.core.files.uploadedfile import SimpleUploadedFile my_model.file_field = SimpleUploadedFile( “best_file_eva.txt”, b”these are the file contents!” # note the b in front of the string [bytes] ) … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)