Mini HOWTO: Programmatically upload a file in Django
Surprisely, there is no any good advice in the Internet how to programmatically upload a file to the FileField field in the Django. I want to cover this issue with the sample that shows how to upload a generic file from the Internet to a Django application. The code is simple: import urllib, mimetypes, os from django.core.files.base import ContentFile #... filename, msg = urllib.urlretrieve(img) ext = mimetypes.guess_extension(msg.type) name, original_ext = os.path.splitext(filename) new_filename = filename if ext != original_ext: new_filename += ext obj.file.save(new_filename, ContentFile(open(filename).read())) First of all, we retrieves a file. urlretrieve returns a tuple <filename, msg>. filename is a name of a temporary file with the downloaded content. msg is a HTTPMessage class instance that contains headers of the file. We use msg to determinate the type of the file. For this guess_extension method is used. It is required for the case when the file is gene...