Python django.forms.FileField() Examples
The following are 30
code examples of django.forms.FileField().
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 also want to check out all available functions/classes of the module
django.forms
, or try the search function
.
Example #1
Source File: submission_filters.py From coursys with GNU General Public License v3.0 | 6 votes |
def field_value(field): """ Returns the value for this BoundField, as rendered in widgets. """ if field.form.is_bound: if isinstance(field.field, FileField) and field.data is None: val = field.form.initial.get(field.name, field.field.initial) else: val = field.data else: val = field.form.initial.get(field.name, field.field.initial) if isinstance(val, collections.Callable): val = val() if val is None: val = '' return val
Example #2
Source File: fields.py From hypha with BSD 3-Clause "New" or "Revised" License | 6 votes |
def clean(self, value, initial): files = value['files'] cleared = value['cleared'] if not files and not cleared: return initial new = [ FileField(validators=[ FileExtensionValidator(allowed_extensions=settings.FILE_ALLOWED_EXTENSIONS) ]).clean(file, initial) for file in files ] if initial: old = [file for i, file in enumerate(initial) if i not in cleared] else: old = [] return old + new
Example #3
Source File: models.py From hypha with BSD 3-Clause "New" or "Revised" License | 6 votes |
def process_form_submission(self, form): cleaned_data = form.cleaned_data for name, field in form.fields.items(): if isinstance(field, FileField): file_data = cleaned_data[name] if file_data: file_name = file_data.name file_name = webform_storage.generate_filename(file_name) upload_to = os.path.join('webform', str(self.id), file_name) saved_file_name = webform_storage.save(upload_to, file_data) file_details_dict = {name: webform_storage.url(saved_file_name)} cleaned_data.update(file_details_dict) else: del cleaned_data[name] form_data = json.dumps(cleaned_data, cls=DjangoJSONEncoder) return self.get_submission_class().objects.create( form_data=form_data, page=self, )
Example #4
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn('myfile-clear', str(form)) form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, 'something.txt') form = DocumentForm(instance=doc) self.assertIn('myfile-clear', str(form)) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) doc = form.save(commit=False) self.assertFalse(doc.myfile)
Example #5
Source File: test_filefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_filefield_changed(self): """ The value of data will more than likely come from request.FILES. The value of initial data will likely be a filename stored in the database. Since its value is of no use to a FileField it is ignored. """ f = FileField() # No file was uploaded and no initial data. self.assertFalse(f.has_changed('', None)) # A file was uploaded and no initial data. self.assertTrue(f.has_changed('', {'filename': 'resume.txt', 'content': 'My resume'})) # A file was not uploaded, but there is initial data self.assertFalse(f.has_changed('resume.txt', None)) # A file was uploaded and there is initial data (file identity is not dealt # with here) self.assertTrue(f.has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'}))
Example #6
Source File: test_filefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_disabled_has_changed(self): f = FileField(disabled=True) self.assertIs(f.has_changed('x', 'y'), False)
Example #7
Source File: test_filefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_filefield_3(self): f = FileField(allow_empty_file=True) self.assertIsInstance(f.clean(SimpleUploadedFile('name', b'')), SimpleUploadedFile)
Example #8
Source File: files.py From python2017 with MIT License | 5 votes |
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
Example #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, 'initial'), 'initial') with self.assertRaises(ValidationError): f.clean(False)
Example #10
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, 'initial'), False)
Example #11
Source File: models.py From hypha with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_document_field(self, field, options): return FileField(**options)
Example #12
Source File: djangoforms.py From python-compat-runtime with Apache License 2.0 | 5 votes |
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)
Example #13
Source File: djangoforms.py From python-compat-runtime with Apache License 2.0 | 5 votes |
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)
Example #14
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={'description': 'Assistance'}) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, '') f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') # Instance can be edited w/out re-uploading the file and existing file should be preserved. f = TextFileForm({'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.file.name, 'tests/test3.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete()
Example #15
Source File: files.py From python2017 with MIT License | 5 votes |
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
Example #16
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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)
Example #17
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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)
Example #18
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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))
Example #19
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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
Example #20
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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)
Example #21
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
def get_internal_type(self): return "FileField"
Example #22
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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
Example #23
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
def check(self, **kwargs): errors = super(FileField, self).check(**kwargs) errors.extend(self._check_unique()) errors.extend(self._check_primary_key()) return errors
Example #24
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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)
Example #25
Source File: files.py From openhgsenti with Apache License 2.0 | 5 votes |
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
Example #26
Source File: files.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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)
Example #27
Source File: files.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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)
Example #28
Source File: files.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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
Example #29
Source File: files.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'name'): value = value.name return super(FileField, self).get_prep_lookup(lookup_type, value)
Example #30
Source File: files.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def get_internal_type(self): return "FileField"