Created
August 15, 2017 19:40
-
-
Save mpasternak/5bdf4f2ff1e86036867e4cca478f581f to your computer and use it in GitHub Desktop.
Django - upload a file to a given model's FileField in a given application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
# save me as yourapp/management/commands/upload_file_to_model.py | |
from argparse import FileType | |
from pathlib import Path | |
from django.contrib.contenttypes.models import ContentType | |
from django.core.management.base import BaseCommand | |
from django.core.files.base import File | |
class Command(BaseCommand): | |
help = 'Uploads a file to a given field in a given model' | |
def add_arguments(self, parser): | |
parser.add_argument("app") | |
parser.add_argument("model") | |
parser.add_argument("pk") | |
parser.add_argument("field") | |
parser.add_argument("path", type=FileType('rb')) | |
def handle(self, *args, **options): | |
obj = ContentType.objects.get_by_natural_key( | |
options['app'].lower(), | |
options['model'].lower() | |
).get_object_for_this_type(pk=options['pk']) | |
try: | |
field = getattr(obj, options['field']) | |
except AttributeError as e: | |
fields = [field.name for field in obj._meta.get_fields()] | |
fields = ", ".join(fields) | |
e.args = (e.args[0] + f". Available names: {fields}", ) | |
raise e | |
field.save( | |
name=Path(options['path'].name).name, | |
content=File(options['path'])) | |
obj.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment