[Answer]-Python script to handle uploaded file via http post

1👍

What you have in request.FILES is InMemoryUploadedFile. You just need to save it somewhere in file system.

This is example method taken from Django docs:

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

0👍

I think you can work with models well. It will be the right way for Django. Here is an example, models.py file:

from django.db import models
from django.conf import settings

import os
import hashlib


def instanced_file(instance, filename):
    splitted_name = filename.split('.')
    extension = splitted_name[-1]
    return os.path.join('files', hashlib.md5(str(instance.id).encode('UTF-8')).hexdigest() + '.' + extension)

class File(models.Model):
    name = models.FileField('File', upload_to = instanced_file)

    def get_file_url(self):
        return '%s%s' % (settings.MEDIA_URL, self.name)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

After the creating models create forms and go on.

👤Noyan

Leave a comment