Python django.db.models.FileField() Examples

The following are 30 code examples for showing how to use django.db.models.FileField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: rearrange_files.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        app_name = options['app']
        model_name = options['model']
        field_name = options['field']

        model = apps.get_model(app_name, model_name)
        fields = model._meta.get_fields()
        matching_fields = [f for f in fields if isinstance(f, models.FileField) and f.name == field_name]
        field = matching_fields[0]
        storage = field.storage

        for o in model.objects.all():
            # threads aren't usually interrupted: https://stackoverflow.com/a/842567/6871666
            t = Thread(target=move_file, args=(model, storage, field_name, field, o))
            t.start()
            t.join() 
Example 2
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 3
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 4
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 5
Project: python   Author: Yeah-Kun   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 6
Project: openhgsenti   Author: drexly   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if field.flatchoices:
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 7
Project: python2017   Author: bpgc-cte   File: utils.py    License: MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 8
Project: devops   Author: madre   File: util.py    License: MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 9
Project: django-unused-media   Author: akolpakov   File: utils.py    License: MIT License 6 votes vote down vote up
def get_file_fields():
    """
        Get all fields which are inherited from FileField
    """

    # get models

    all_models = apps.get_models()

    # get fields

    fields = []

    for model in all_models:
        for field in model._meta.get_fields():
            if isinstance(field, models.FileField):
                fields.append(field)

    return fields 
Example 10
Project: donation-tracker   Author: GamesDoneQuick   File: serializers.py    License: Apache License 2.0 5 votes vote down vote up
def handle_field(self, obj, field):
        if isinstance(field, models.FileField):
            value = field.value_from_object(obj)
            self._current[field.name] = value.url if value else ''
        elif isinstance(field, models.DecimalField):
            value = field.value_from_object(obj)
            self._current[field.name] = float(value) if value else value
        else:
            super(TrackerSerializer, self).handle_field(obj, field) 
Example 11
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def sendfile(self, upfile, response):
        """
        Send the contents of the file as the response, given a FileField object to read from.
        """
        path, filename = os.path.split(upfile.name)
        response['Content-Disposition'] = 'inline; filename="' + filename + '"'
        try:
            upfile.open('rb')
        except IOError:
            response['Content-type'] = "text/plain"
            response.write("File missing. It has likely been archived.")
            return

        for data in upfile:
            response.write(data) 
Example 12
Project: coursys   Author: sfu-fas   File: rearrange_files.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument('app', type=str, help='the app to work in')
        parser.add_argument('model', type=str, help='the model class to work on')
        parser.add_argument('field', type=str, help='the FileField in the model') 
Example 13
Project: StormOnline   Author: stormsha   File: wizard.py    License: Apache License 2.0 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 14
Project: django-idcops   Author: Wenvki   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field, html=True, only_date=True):
    if getattr(field, 'flatchoices', None):
        if html and field.name == 'color' and value:
            return make_color_icon(value)
        return dict(field.flatchoices).get(value, '')
    elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
        return make_boolean_icon(value)
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        boolchoice = {False: "否", True: "是"}
        return boolchoice.get(value)
    elif value is None:
        return ""
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.ForeignKey) and value:
        rel_obj = field.related_model.objects.get(pk=value)
        if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
            text_color = rel_obj.color
            if not text_color:
                text_color = 'text-info'
            safe_value = format_html(
                '<span class="text-{}">{}</span>', text_color, rel_obj.text)
            return safe_value
        return force_text(rel_obj)
    elif isinstance(field, models.TextField) and value:
        return force_text(value)
    elif isinstance(field, models.DateTimeField):
        if only_date:
            return formats.date_format(value)
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value) 
Example 15
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 16
Project: GTDWeb   Author: lanbing510   File: options.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        opts = self.model._meta
        app_label = opts.app_label
        preserved_filters = self.get_preserved_filters(request)
        form_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, form_url)
        view_on_site_url = self.get_view_on_site_url(obj)
        context.update({
            'add': add,
            'change': change,
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, obj),
            'has_delete_permission': self.has_delete_permission(request, obj),
            'has_file_field': True,  # FIXME - this should check if form or formsets have a FileField,
            'has_absolute_url': view_on_site_url is not None,
            'absolute_url': view_on_site_url,
            'form_url': form_url,
            'opts': opts,
            'content_type_id': get_content_type_for_model(self.model).pk,
            'save_as': self.save_as,
            'save_on_top': self.save_on_top,
            'to_field_var': TO_FIELD_VAR,
            'is_popup_var': IS_POPUP_VAR,
            'app_label': app_label,
        })
        if add and self.add_form_template is not None:
            form_template = self.add_form_template
        else:
            form_template = self.change_form_template

        request.current_app = self.admin_site.name

        return TemplateResponse(request, form_template or [
            "admin/%s/%s/change_form.html" % (app_label, opts.model_name),
            "admin/%s/change_form.html" % app_label,
            "admin/change_form.html"
        ], context) 
Example 17
Project: bioforum   Author: reBiocoder   File: models.py    License: MIT License 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Construct and return a model instance from the bound ``form``'s
    ``cleaned_data``, but do not save the returned instance to the database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Leave defaults for fields that aren't in POST data, except for
        # checkbox inputs because they don't appear in POST data if not checked.
        if (f.has_default() and
                form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance


# ModelForms ################################################################# 
Example 18
Project: bioforum   Author: reBiocoder   File: options.py    License: MIT License 5 votes vote down vote up
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        opts = self.model._meta
        app_label = opts.app_label
        preserved_filters = self.get_preserved_filters(request)
        form_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, form_url)
        view_on_site_url = self.get_view_on_site_url(obj)
        context.update({
            'add': add,
            'change': change,
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, obj),
            'has_delete_permission': self.has_delete_permission(request, obj),
            'has_file_field': True,  # FIXME - this should check if form or formsets have a FileField,
            'has_absolute_url': view_on_site_url is not None,
            'absolute_url': view_on_site_url,
            'form_url': form_url,
            'opts': opts,
            'content_type_id': get_content_type_for_model(self.model).pk,
            'save_as': self.save_as,
            'save_on_top': self.save_on_top,
            'to_field_var': TO_FIELD_VAR,
            'is_popup_var': IS_POPUP_VAR,
            'app_label': app_label,
        })
        if add and self.add_form_template is not None:
            form_template = self.add_form_template
        else:
            form_template = self.change_form_template

        request.current_app = self.admin_site.name

        return TemplateResponse(request, form_template or [
            "admin/%s/%s/change_form.html" % (app_label, opts.model_name),
            "admin/%s/change_form.html" % app_label,
            "admin/change_form.html"
        ], context) 
Example 19
Project: weibo-analysis-system   Author: Superbsco   File: wizard.py    License: MIT License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 20
Project: mangaki   Author: mangaki   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def poster_url(self):
        if self.int_poster:  # 1. Internal poster as FileField
            return self.int_poster.url
        int_path = '/static/img/posters/{}.jpg'.format(self.id)  # 2. Retrieved
        if os.path.isfile(os.path.join('mangaki', 'mangaki', int_path)):
            return int_path
        else:
            return self.ext_poster  # 3. Otherwise, external link 
Example 21
Project: osler   Author: SaturdayNeighborhoodHealthClinic   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_filepath(instance, filename):
    '''
        Produces a unique file path for the upload_to of a FileField. This is
        important because any URL is 1) transmitted unencrypted and 2)
        automatically referred to any libraries we include (i.e. Bootstrap,
        AngularJS).

        The produced path is of the form:
        "[model name]/[field name]/[random name].[filename extension]".

        Copypasta from https://djangosnippets.org/snippets/2819/
    '''


    field_name = 'image'
    carry_on = True
    while carry_on:
        new_filename = "%s.%s" % (User.objects.make_random_password(48),
                                  filename.split('.')[-1])
        #path = '/'.join([instance.__class__.__name__.lower(),field_name, new_filename])

        path = new_filename

        # if the file already exists, try again to generate a new filename
        carry_on = os.path.isfile(os.path.join(settings.MEDIA_ROOT, path))

    return path 
Example 22
Project: myblog   Author: myminwang   File: wizard.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 23
Project: CTF_AWD_Platform   Author: xuchaoa   File: wizard.py    License: MIT License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 24
Project: django_OA   Author: abaoMAO   File: wizard.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 25
Project: django-linguist   Author: ulule   File: test_metaclass.py    License: MIT License 5 votes vote down vote up
def test_create_translation_field_has_correct_descriptor(self):
        field = create_translation_field(models.fields.CharField(), "en")
        assert field.descriptor_class == TranslationDescriptor

        field = create_translation_field(models.FileField(), "en")
        assert field.descriptor_class == files.FileTranslationDescriptor

        field = create_translation_field(models.ImageField(), "en")
        assert field.descriptor_class == files.FileTranslationDescriptor

        field = create_translation_field(models.fields.TextField(), "en")
        assert field.descriptor_class == TranslationDescriptor 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: models.py    License: MIT License 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Construct and return a model instance from the bound ``form``'s
    ``cleaned_data``, but do not save the returned instance to the database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Leave defaults for fields that aren't in POST data, except for
        # checkbox inputs because they don't appear in POST data if not checked.
        if (f.has_default() and
                form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance


# ModelForms ################################################################# 
Example 27
Project: django-fine-uploader   Author: douglasmiranda   File: admin.py    License: MIT License 5 votes vote down vote up
def fineuploader_setting(self, request: HttpRequest):
        post_info = request.POST.dict()
        if type(self.formfield_overrides.get(FileField).get('widget')) is widgets.FineUploaderWidget:
            model_fields = self.model._meta.fields
            file_fields = {}
            file_fields_name = []
            for field in model_fields:
                if field.get_internal_type() is 'FileField':
                    file_fields_name.append(field.name)
            if request.method == 'POST':
                print(file_fields_name)
                for name in file_fields_name:
                    file_uploader = cache.get(request.POST.get(name))
                    if file_uploader is None:
                        return
                        # raise forms.ValidationError("There is no file in the field.")
                    file_path = file_uploader.storage.path(file_uploader.real_path)
                    post_info[name] = SimpleUploadedFile(
                        file_uploader.filename,
                        open(file_path, 'rb').read()
                    )
                    request.POST = post_info
                    folder_path = file_uploader.storage.path(file_uploader.file_path)
                    try:
                        shutil.rmtree(folder_path)
                    except (OSError, PermissionError):
                        pass
        # return post_info 
Example 28
Project: wagtailstreamforms   Author: labd   File: test_form_submission_file.py    License: MIT License 5 votes vote down vote up
def test_file(self):
        field = self.get_field(FormSubmissionFile, "file")
        self.assertModelField(field, models.FileField) 
Example 29
Project: python   Author: Yeah-Kun   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Leave defaults for fields that aren't in POST data, except for
        # checkbox inputs because they don't appear in POST data if not checked.
        if (f.has_default() and
                form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance


# ModelForms ################################################################# 
Example 30
Project: python   Author: Yeah-Kun   File: options.py    License: Apache License 2.0 5 votes vote down vote up
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        opts = self.model._meta
        app_label = opts.app_label
        preserved_filters = self.get_preserved_filters(request)
        form_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, form_url)
        view_on_site_url = self.get_view_on_site_url(obj)
        context.update({
            'add': add,
            'change': change,
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, obj),
            'has_delete_permission': self.has_delete_permission(request, obj),
            'has_file_field': True,  # FIXME - this should check if form or formsets have a FileField,
            'has_absolute_url': view_on_site_url is not None,
            'absolute_url': view_on_site_url,
            'form_url': form_url,
            'opts': opts,
            'content_type_id': get_content_type_for_model(self.model).pk,
            'save_as': self.save_as,
            'save_on_top': self.save_on_top,
            'to_field_var': TO_FIELD_VAR,
            'is_popup_var': IS_POPUP_VAR,
            'app_label': app_label,
        })
        if add and self.add_form_template is not None:
            form_template = self.add_form_template
        else:
            form_template = self.change_form_template

        request.current_app = self.admin_site.name

        return TemplateResponse(request, form_template or [
            "admin/%s/%s/change_form.html" % (app_label, opts.model_name),
            "admin/%s/change_form.html" % app_label,
            "admin/change_form.html"
        ], context)