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. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 weeks, 5 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 1 week ago

Comments

Please login first before commenting.