Login

Place a file in an object from command-line (Python 3.x only)

Author:
mpasternak
Posted:
July 19, 2017
Language:
Python
Version:
1.10
Score:
0 (after 0 ratings)

You can place this snippet in management/commands/ and have it upload files from disk into objects in your database.

Usage: python manage.py upload_file_to_model myapp mymodel myfield 1 field_name /some/file/path

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# -*- 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()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.