我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.FileField()。
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
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
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})
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
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)
def check(self, **kwargs): errors = super(FileField, self).check(**kwargs) errors.extend(self._check_unique()) errors.extend(self._check_primary_key()) return errors
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
def get_internal_type(self): return "FileField"
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)
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))
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)
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)
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)
def prepare_form(self): class MyForm(forms.Form): media_file = forms.FileField(label='??????') if_load = forms.BooleanField(label='??????', required=False)
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)
def check_fields(self): for name, field in self.form_obj.fields.items(): if isinstance(field,forms.FileField): self._has_file_field = True
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))))
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)))
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()
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)
def check(self, **kwargs): errors = super(FileField, self).check(**kwargs) errors.extend(self._check_primary_key()) errors.extend(self._check_upload_to()) return errors
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
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)
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)