Python django.forms 模块,FileField() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.FileField()

项目:Strassengezwitscher    作者:Strassengezwitscher    | 项目源码 | 文件源码
def files_are_valid(cls, request):
        """Takes a request and returns True if the uploaded files are valid. Otherwise returns found errors."""
        uploaded_files = request.FILES.getlist('files')
        if len(uploaded_files) >= 2:
            # Django's validation does only work for a single file. When uploading multiple files only the last one gets
            # checked for validity. We could subclass FileField to suit our needs. Somebody did that already:
            # https://github.com/Chive/django-multiupload
            # However, the pain of the following workaround is not strong enough to add another dependency.
            # As we have multiple files we create a new form with the same data but only a single file for each file
            # and check the new form's validity.
            # Another alternative would be not relying on Django's automatic FileField validation at all and just do
            # that tiny bit of validation ourselves for all files in request.FILES.
            for uploaded_file in uploaded_files:
                request.FILES['files'] = uploaded_file
                temp_form = cls(request.POST, request.FILES)
                if not temp_form.is_valid():
                    return temp_form.errors
        return True
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def pre_save(self, model_instance, add):
        "Returns field's value just before saving."
        file = super(FileField, self).pre_save(model_instance, add)
        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save(file.name, file, save=False)
        return file
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def _save_to_answer(self, field, answer, value):
        action = 'pretalx.submission.answer' + ('update' if answer.pk else 'create')
        if isinstance(field, forms.ModelMultipleChoiceField):
            answstr = ', '.join([str(o) for o in value])
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.answer = answstr
            answer.options.add(*value)
        elif isinstance(field, forms.ModelChoiceField):
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.options.add(value)
            answer.answer = value.answer
        elif isinstance(field, forms.FileField):
            if isinstance(value, UploadedFile):
                answer.answer_file.save(value.name, value)
                answer.answer = 'file://' + value.name
            value = answer.answer
        else:
            answer.answer = value
        answer.log_action(action, person=self.request_user, data={'answer': value})
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, 'name'):
            return self.name == other.name
        return self.name == other
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
        self._primary_key_set_explicitly = 'primary_key' in kwargs
        self._unique_set_explicitly = 'unique' in kwargs

        self.storage = storage or default_storage
        self.upload_to = upload_to

        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(FileField, self).__init__(verbose_name, name, **kwargs)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def check(self, **kwargs):
        errors = super(FileField, self).check(**kwargs)
        errors.extend(self._check_unique())
        errors.extend(self._check_primary_key())
        return errors
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def deconstruct(self):
        name, path, args, kwargs = super(FileField, self).deconstruct()
        if kwargs.get("max_length") == 100:
            del kwargs["max_length"]
        kwargs['upload_to'] = self.upload_to
        if self.storage is not default_storage:
            kwargs['storage'] = self.storage
        return name, path, args, kwargs
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_internal_type(self):
        return "FileField"
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_prep_value(self, value):
        "Returns field's value prepared for saving into a database."
        value = super(FileField, self).get_prep_value(value)
        # Need to convert File objects provided via a form to unicode for database insertion
        if value is None:
            return None
        return six.text_type(value)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def contribute_to_class(self, cls, name, **kwargs):
        super(FileField, self).contribute_to_class(cls, name, **kwargs)
        setattr(cls, self.name, self.descriptor_class(self))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
        # If a file has been provided previously, then the form doesn't require
        # that a new file is provided this time.
        # The code to mark the form field as not required is used by
        # form_for_instance, but can probably be removed once form_for_instance
        # is gone. ModelForm uses a different method to check for an existing file.
        if 'initial' in kwargs:
            defaults['required'] = False
        defaults.update(kwargs)
        return super(FileField, self).formfield(**defaults)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __set__(self, instance, value):
        previous_file = instance.__dict__.get(self.field.name)
        super(ImageFileDescriptor, self).__set__(instance, value)

        # To prevent recalculating image dimensions when we are instantiating
        # an object from the database (bug #11084), only update dimensions if
        # the field had a value before this assignment.  Since the default
        # value for FileField subclasses is an instance of field.attr_class,
        # previous_file will only be None when we are called from
        # Model.__init__().  The ImageField.update_dimension_fields method
        # hooked up to the post_init signal handles the Model.__init__() cases.
        # Assignment happening outside of Model.__init__() will trigger the
        # update right here.
        if previous_file is not None:
            self.field.update_dimension_fields(instance, force=True)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.max_length = kwargs.pop('max_length', None)
        self.allow_empty_file = kwargs.pop('allow_empty_file', False)
        super(FileField, self).__init__(*args, **kwargs)
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def prepare_form(self):
        class MyForm(forms.Form):
            media_file = forms.FileField(label='??????')
            if_load = forms.BooleanField(label='??????', required=False)
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def prepare_form(self):
        class MyForm(forms.Form):
            name = forms.CharField(label='??')
            parent = forms.IntegerField(label='???', required=False, widget=widgets.ForeignKeyPopupWidget(self, models.MediaFile, 'id'))
            number = forms.CharField(label='???', required=False, help='????????????')
            media_file = forms.FileField(label='??????', required=False)
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def check_fields(self):
        for name, field in self.form_obj.fields.items():
            if isinstance(field,forms.FileField):
                self._has_file_field = True
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, 'name'):
            return self.name == other.name
        return self.name == other
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
        self._primary_key_set_explicitly = 'primary_key' in kwargs
        self._unique_set_explicitly = 'unique' in kwargs

        self.storage = storage or default_storage
        self.upload_to = upload_to

        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(FileField, self).__init__(verbose_name, name, **kwargs)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def check(self, **kwargs):
        errors = super(FileField, self).check(**kwargs)
        errors.extend(self._check_unique())
        errors.extend(self._check_primary_key())
        return errors
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def deconstruct(self):
        name, path, args, kwargs = super(FileField, self).deconstruct()
        if kwargs.get("max_length") == 100:
            del kwargs["max_length"]
        kwargs['upload_to'] = self.upload_to
        if self.storage is not default_storage:
            kwargs['storage'] = self.storage
        return name, path, args, kwargs
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_internal_type(self):
        return "FileField"
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def pre_save(self, model_instance, add):
        "Returns field's value just before saving."
        file = super(FileField, self).pre_save(model_instance, add)
        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save(file.name, file, save=False)
        return file
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def contribute_to_class(self, cls, name, **kwargs):
        super(FileField, self).contribute_to_class(cls, name, **kwargs)
        setattr(cls, self.name, self.descriptor_class(self))
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_directory_name(self):
        warnings.warn(
            'FileField now delegates file name and folder processing to the '
            'storage. get_directory_name() will be removed in Django 2.0.',
            RemovedInDjango20Warning, stacklevel=2
        )
        return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_filename(self, filename):
        warnings.warn(
            'FileField now delegates file name and folder processing to the '
            'storage. get_filename() will be removed in Django 2.0.',
            RemovedInDjango20Warning, stacklevel=2
        )
        return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
        # If a file has been provided previously, then the form doesn't require
        # that a new file is provided this time.
        # The code to mark the form field as not required is used by
        # form_for_instance, but can probably be removed once form_for_instance
        # is gone. ModelForm uses a different method to check for an existing file.
        if 'initial' in kwargs:
            defaults['required'] = False
        defaults.update(kwargs)
        return super(FileField, self).formfield(**defaults)
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def __init__(self, is_test_source=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if is_test_source:
            self.fields['code'] = forms.CharField(widget=forms.Textarea)
        else:
            self.fields['file'] = forms.FileField()
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, 'name'):
            return self.name == other.name
        return self.name == other
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
        self._primary_key_set_explicitly = 'primary_key' in kwargs

        self.storage = storage or default_storage
        self.upload_to = upload_to

        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(FileField, self).__init__(verbose_name, name, **kwargs)
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def check(self, **kwargs):
        errors = super(FileField, self).check(**kwargs)
        errors.extend(self._check_primary_key())
        errors.extend(self._check_upload_to())
        return errors
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def deconstruct(self):
        name, path, args, kwargs = super(FileField, self).deconstruct()
        if kwargs.get("max_length") == 100:
            del kwargs["max_length"]
        kwargs['upload_to'] = self.upload_to
        if self.storage is not default_storage:
            kwargs['storage'] = self.storage
        return name, path, args, kwargs
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_internal_type(self):
        return "FileField"
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def pre_save(self, model_instance, add):
        "Returns field's value just before saving."
        file = super(FileField, self).pre_save(model_instance, add)
        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save(file.name, file.file, save=False)
        return file
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def contribute_to_class(self, cls, name, **kwargs):
        super(FileField, self).contribute_to_class(cls, name, **kwargs)
        setattr(cls, self.name, self.descriptor_class(self))
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_directory_name(self):
        warnings.warn(
            'FileField now delegates file name and folder processing to the '
            'storage. get_directory_name() will be removed in Django 2.0.',
            RemovedInDjango20Warning, stacklevel=2
        )
        return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_filename(self, filename):
        warnings.warn(
            'FileField now delegates file name and folder processing to the '
            'storage. get_filename() will be removed in Django 2.0.',
            RemovedInDjango20Warning, stacklevel=2
        )
        return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
        # If a file has been provided previously, then the form doesn't require
        # that a new file is provided this time.
        # The code to mark the form field as not required is used by
        # form_for_instance, but can probably be removed once form_for_instance
        # is gone. ModelForm uses a different method to check for an existing file.
        if 'initial' in kwargs:
            defaults['required'] = False
        defaults.update(kwargs)
        return super(FileField, self).formfield(**defaults)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, 'name'):
            return self.name == other.name
        return self.name == other
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
        self._primary_key_set_explicitly = 'primary_key' in kwargs
        self._unique_set_explicitly = 'unique' in kwargs

        self.storage = storage or default_storage
        self.upload_to = upload_to

        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(FileField, self).__init__(verbose_name, name, **kwargs)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def check(self, **kwargs):
        errors = super(FileField, self).check(**kwargs)
        errors.extend(self._check_unique())
        errors.extend(self._check_primary_key())
        return errors
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def deconstruct(self):
        name, path, args, kwargs = super(FileField, self).deconstruct()
        if kwargs.get("max_length") == 100:
            del kwargs["max_length"]
        kwargs['upload_to'] = self.upload_to
        if self.storage is not default_storage:
            kwargs['storage'] = self.storage
        return name, path, args, kwargs
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def get_internal_type(self):
        return "FileField"
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def get_prep_value(self, value):
        "Returns field's value prepared for saving into a database."
        value = super(FileField, self).get_prep_value(value)
        # Need to convert File objects provided via a form to unicode for database insertion
        if value is None:
            return None
        return six.text_type(value)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def pre_save(self, model_instance, add):
        "Returns field's value just before saving."
        file = super(FileField, self).pre_save(model_instance, add)
        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save(file.name, file, save=False)
        return file
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def contribute_to_class(self, cls, name, **kwargs):
        super(FileField, self).contribute_to_class(cls, name, **kwargs)
        setattr(cls, self.name, self.descriptor_class(self))
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
        # If a file has been provided previously, then the form doesn't require
        # that a new file is provided this time.
        # The code to mark the form field as not required is used by
        # form_for_instance, but can probably be removed once form_for_instance
        # is gone. ModelForm uses a different method to check for an existing file.
        if 'initial' in kwargs:
            defaults['required'] = False
        defaults.update(kwargs)
        return super(FileField, self).formfield(**defaults)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def __set__(self, instance, value):
        previous_file = instance.__dict__.get(self.field.name)
        super(ImageFileDescriptor, self).__set__(instance, value)

        # To prevent recalculating image dimensions when we are instantiating
        # an object from the database (bug #11084), only update dimensions if
        # the field had a value before this assignment.  Since the default
        # value for FileField subclasses is an instance of field.attr_class,
        # previous_file will only be None when we are called from
        # Model.__init__().  The ImageField.update_dimension_fields method
        # hooked up to the post_init signal handles the Model.__init__() cases.
        # Assignment happening outside of Model.__init__() will trigger the
        # update right here.
        if previous_file is not None:
            self.field.update_dimension_fields(instance, force=True)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def get_form_field(self, **kwargs):
    """Return a Django form field appropriate for a blob property.

    This defaults to a forms.FileField instance when using Django 0.97
    or later.  For 0.96 this returns None, as file uploads are not
    really supported in that version.
    """
    if not hasattr(forms, 'FileField'):
      return None
    defaults = {'form_class': forms.FileField}
    defaults.update(kwargs)
    return super(BlobProperty, self).get_form_field(**defaults)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def make_value_from_form(self, value):
    """Convert a form value to a property value.

    This extracts the content from the UploadedFile instance returned
    by the FileField instance.
    """
    if have_uploadedfile and isinstance(value, uploadedfile.UploadedFile):
      if not self.form_value:
        self.form_value = value.read()
      b = db.Blob(self.form_value)
      return b
    return super(BlobProperty, self).make_value_from_form(value)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def __eq__(self, other):
        # Older code may be expecting FileField values to be simple strings.
        # By overriding the == operator, it can remain backwards compatibility.
        if hasattr(other, 'name'):
            return self.name == other.name
        return self.name == other