Here are the examples of the python api django.forms.FileField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
16 Examples
3
View Complete Implementation : param.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
def __getattr__(self, name):
if name not in self._cleaned_data:
form = self._bounded_form
if name not in form.fields:
raise AttributeError(name)
field = form.fields[name]
value = field.widget.value_from_datadict(
form.data, form.files, form.add_prefix(name))
if isinstance(field, forms.FileField):
initial = self.initial.get(name, field.initial)
value = field.clean(value, initial)
else:
value = field.clean(value)
self._cleaned_data[name] = value
self._clean_dependency(name)
return self._cleaned_data[name]
3
View Complete Implementation : files.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
def formfield(self, **kwargs):
defaults = {'form_clast': 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)
3
View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
Copyright MIT License
Author : labd
def test_singlefile_field(self):
data = self.get_form_field_data('singlefile')
cls = wsf_fields.SingleFileField()
field = cls.get_formfield(data)
self.astertIsInstance(field, forms.FileField)
self.astertIsInstance(field.widget, forms.widgets.FileInput)
self.astertEqual(field.label, data['label'])
self.astertEqual(field.required, data['required'])
self.astertEqual(field.help_text, data['help_text'])
3
View Complete Implementation : test_fields.py
Copyright MIT License
Author : labd
Copyright MIT License
Author : labd
def test_multifile_field(self):
data = self.get_form_field_data('multifile')
cls = wsf_fields.MultiFileField()
field = cls.get_formfield(data)
self.astertIsInstance(field, forms.FileField)
self.astertIsInstance(field.widget, forms.widgets.FileInput)
self.astertEqual(field.label, data['label'])
self.astertEqual(field.required, data['required'])
self.astertEqual(field.help_text, data['help_text'])
3
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_filefield_2(self):
f = FileField(max_length=5)
with self.astertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'"):
f.clean(SimpleUploadedFile('test_maxlength.txt', b'hello world'))
self.astertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
self.astertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
self.astertIsInstance(f.clean(SimpleUploadedFile('name', b'Some File Content')), SimpleUploadedFile)
3
View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_filefield(self):
e = {
'required': 'REQUIRED',
'invalid': 'INVALID',
'missing': 'MISSING',
'empty': 'EMPTY FILE',
}
f = FileField(error_messages=e)
self.astertFormErrors(['REQUIRED'], f.clean, '')
self.astertFormErrors(['INVALID'], f.clean, 'abc')
self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))
3
View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
Copyright Apache License 2.0
Author : ooknosi
def test_MaterialForm_materializes_FileField(self):
"""django.forms.widgets.ClearableFileInput should be converted to
material_widgets.widgets.MaterialClearableFileInput.
"""
clast ClearableFileInputForm(MaterialForm):
clearable_file_input = forms.FileField()
form = ClearableFileInputForm()
self.astertEqual(
type(form.fields['clearable_file_input'].widget),
widgets.MaterialClearableFileInput,
)
3
View Complete Implementation : files.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def formfield(self, **kwargs):
return super().formfield(**{
'form_clast': forms.FileField,
'max_length': self.max_length,
**kwargs,
})
3
View Complete Implementation : test_file_field.py
Copyright MIT License
Author : SectorLabs
Copyright MIT License
Author : SectorLabs
@staticmethod
def test_formfield():
"""Tests whether the :see:formfield function correctly returns a valid
form."""
form_field = LocalizedFileField().formfield()
astert isinstance(form_field, LocalizedFileFieldForm)
astert isinstance(form_field, forms.FileField)
astert isinstance(form_field.widget, LocalizedFileWidget)
3
View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : Unicaronas
Copyright GNU Affero General Public License v3.0
Author : Unicaronas
def __init__(self, options={}, widget_kwargs={}, widget=None, *args, **kwargs):
widget = CustomCroppieImageRatioWidget(
options=options,
**widget_kwargs
)
fields = (
forms.FileField(),
forms.CharField(),
forms.CharField(),
forms.CharField(),
forms.CharField(),
)
super(CroppieField, self).__init__(
fields=fields, widget=widget, *args, **kwargs)
0
View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
@clastmethod
def get_initkwargs(cls, form_list=None, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
"""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
clastes or tuples of (`step_name`, `form_clast`). If you past a list
of forms, the wizardview will convert the clast list to
(`zero_based_counter`, `form_clast`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary whose values are model
instances if the step is based on a ``ModelForm`` and querysets if
the step is based on a ``ModelFormSet``. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the wizardview instance as the only argument.
If the return value is true, the step's form will be used.
"""
kwargs.update({
'initial_dict': initial_dict or kwargs.pop('initial_dict',
getattr(cls, 'initial_dict', None)) or {},
'instance_dict': instance_dict or kwargs.pop('instance_dict',
getattr(cls, 'instance_dict', None)) or {},
'condition_dict': condition_dict or kwargs.pop('condition_dict',
getattr(cls, 'condition_dict', None)) or {}
})
form_list = form_list or kwargs.pop('form_list',
getattr(cls, 'form_list', None)) or []
computed_form_list = SortedDict()
astert len(form_list) > 0, 'at least one form is needed'
# walk through the pasted form list
for i, form in enumerate(form_list):
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
computed_form_list[six.text_type(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
computed_form_list[six.text_type(i)] = form
# walk through the new created list of forms
for form in six.itervalues(computed_form_list):
if issubclast(form, formsets.BaseFormSet):
# if the element is based on BaseFormSet (FormSet/ModelFormSet)
# we need to override the form variable.
form = form.form
# check if any form contains a FileField, if yes, we need a
# file_storage added to the wizardview (by subclasting).
for field in six.itervalues(form.base_fields):
if (isinstance(field, forms.FileField) and
not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured(
"You need to define 'file_storage' in your "
"wizard view in order to handle file uploads.")
# build the kwargs for the wizardview instances
kwargs['form_list'] = computed_form_list
return kwargs
0
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_filefield_1(self):
f = FileField()
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('', '')
self.astertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None, '')
self.astertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
no_file_msg = "'No file was submitted. Check the encoding type on the form.'"
with self.astertRaisesMessage(ValidationError, no_file_msg):
f.clean(SimpleUploadedFile('', b''))
with self.astertRaisesMessage(ValidationError, no_file_msg):
f.clean(SimpleUploadedFile('', b''), '')
self.astertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
with self.astertRaisesMessage(ValidationError, no_file_msg):
f.clean('some content that is not a file')
with self.astertRaisesMessage(ValidationError, "'The submitted file is empty.'"):
f.clean(SimpleUploadedFile('name', None))
with self.astertRaisesMessage(ValidationError, "'The submitted file is empty.'"):
f.clean(SimpleUploadedFile('name', b''))
self.astertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
self.astertIsInstance(
f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode())),
SimpleUploadedFile
)
self.astertIsInstance(
f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'),
SimpleUploadedFile
)
0
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_filefield_3(self):
f = FileField(allow_empty_file=True)
self.astertIsInstance(f.clean(SimpleUploadedFile('name', b'')), SimpleUploadedFile)
0
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
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.astertFalse(f.has_changed('', None))
# A file was uploaded and no initial data.
self.astertTrue(f.has_changed('', {'filename': 'resume.txt', 'content': 'My resume'}))
# A file was not uploaded, but there is initial data
self.astertFalse(f.has_changed('resume.txt', None))
# A file was uploaded and there is initial data (file idensaty is not dealt
# with here)
self.astertTrue(f.has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'}))
0
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_disabled_has_changed(self):
f = FileField(disabled=True)
self.astertIs(f.has_changed('x', 'y'), False)
0
View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_file_picklable(self):
self.astertIsInstance(pickle.loads(pickle.dumps(FileField())), FileField)