How to serialize multiple files in Django - python

I am trying to serialize multiple files, send the files using 'Postman' and have tried several ways to save several files at once.
This is the model:
class PrtFiles(models.Model):
file_name = models.FileField(null=True, blank=True)
And I getting this request in my view in Django:
<MultiValueDict: {'file_name[0]': [<InMemoryUploadedFile: Inventario Personal_Users [SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>], 'file_name[1]': [<InMemoryUploadedFile: Planilla_de_Usuarios_MEL [NEW][SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}>
Whit this Request in Postman:
enter image description here
Any method that to do that?
P.S. I'm beginner with Django, thanks beforehand.

Iterate over the files where you can see the request.
def save_to_model(files):
for f in files:
m = PrtFiles()
m.file_name = f
m.save()
This is the idea what you can do it. I hope you'll implement a better way.

Related

How to create a code field in django form and save it as a json to the db

I am having a usecase where I want to have a code snippet field in django and use that code field value and save it as a json in the DB.
class TestForm(forms.Form):
rule_name = forms.CharField(max_length=200)
rule_code = forms.CharField(max_length=200)
the rule_code field should be able to accept code and when reading I should be able to parse as json.
eg:
rule_code = a+b
while parsing it should be as json.
eg:
{"data":{"lval":"a", "rval": "b", "log":"+"}}
any suggestion will be helpful. Thanks
It's called a JSONField, and it's part of django's core framework:
my_json = models.JSONField(encoder=None, decoder=None, **options)
Django Documentation here.

Duplicate in Object storage

I use a Minio-backend in the Django app. I have a feature that users can use the object storage(user online gallery), and Also, users can upload a new image from the device to create a post. But when I use the object storage images and create an image, images duplicate in object storage(because each time I create a post, I want to upload new images( images that upload locally) in object storage). What should I do to prevent these duplicates?
It is my model:
class MediaStorage(models.Model):
file = models.FileField(verbose_name="Object Upload",
storage=MinioBackend(bucket_name='django-backend-dev-private'),
upload_to=iso_date_prefix)
this is my create new post :
class CreatePostView(generics.CreateAPIView):
...
def post(self, request, *args, **kwargs):
user = request.user
data = request.data
...
for media_file in post_files:
file_team=post_team
f = MediaStorage.objects.create(team=file_team,owner=user)
f.media=media_file
f.save()
post.multimedia.add(f)
return Response(post_serializer.PostSerializer(post).data, status=status.HTTP_201_CREATED)
Thank you so much.
I think you shouldn't upload directly,u could get image md5 first,and a attr to MediaStorage to save md5 value,before upload check is there same md5 in DB,If has that may you already upload this image before

Unable to save fileattachment into Django Model FileField

I am currently integrating exchange server email to my application. I am able to retrieve attachments from my emails using exchangelib. I am trying to save the attachments into my Django model filefield. However, it is not working with different errors based on different solutions I tried. Any help is appreciated. Thank you. Below are some of my code:
models.py
class Attachments(models.Model):
name = models.CharField(max_length=255)
attachment = models.FileField(upload_to="attachments/")
views.py
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
attachmentlist.append(attachment.name)
saveattachments = Attachments(
name=attachment.name,
attachment=(attachment.content)
)
saveattachments.save()
Please look an following snippet and try to do same in you code
from django.core.files.base import ContentFile
...
saveattachments = Attachments(name=attachment.name)
saveattachments.attachment.save(attachment.name, ContentFile(attachment.content))
saveattachments.save()

Django Rest framework: I want my GET response to be a JSON object of links to all files in my media directory on my local machine. How do i do this?

My Project structure:
myproject
--*
--*
--media
--*
--*
I want to allow users to access to my media directory: I want them to be able to read and download all files in my media directory and I want them to be able to write files to my media directory.
How can I accomplish this using Django rest framework?
Assume that there are 2 files in my media directory: I want to return the following JSON object as a response to a GET request:
{
file1: link_to_example1.txt
}
{
file2: link_to_example2.txt
}
How do I do this -- what should my app's model.py, views.py and maybe serializers.py look like?
We can start with simple thing like this. Every time user upload a file, one record is created in the model. If you plan to add/remove file without using your system, you may need a method to sync the latest folder content with your model's records.
class MediaFile(models.Model):
media_file = models.FileField()
uploaded = models.DateTimeField(auto_now_add=True)
class MediaFileSerializer(serializers.ListSerializer):
class Meta:
model = MediaFile
fields = ('media_file',)
class MediaViewSet(viewsets.ViewSet):
"""
A simple ViewSet for listing or retrieving MediaList.
"""
serializer_class = MediaFileSerializer
Then you can study how to upload file with Django and DRF.

400 error on django filefield model save

I'm using django 1.6.5 on python 2.7, and am trying to upload images with a form. My MEDIA_URL is '/uploads', MEDIA_ROOT='...../projectroot/uploads'.
My model:
class Picture(models.Model):
person = models.ForeignKey(User)
image = models.ImageField(upload_to='/images')
My Form field:
images = forms.ImageField(widget=forms.FileInput(), required=False)
My form saving:
image = self.cleaned_data['images']
picture = Picture(park=model, image=image)
picture.save()
I have tried setting the uploads folder permissions to 777 recursively, so django definitely has write access, but that didn't work. Somebody said the enctype on the form mattered, so I've set that to "multipart/form-data".
If it helps, only the actual saving creates the error (although that may have something to do with django just using lazy functions)

Categories