Python django.forms.FileField() Examples

The following are 30 code examples for showing how to use django.forms.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.forms , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: submission_filters.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: hypha   Author: OpenTechFund   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: hypha   Author: OpenTechFund   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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
Project: djongo   Author: nesdis   File: test_filefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        f = forms.FileField(required=self.config['required'],
            label=self.config['label'],
            help_text=self.config['help_text'],
            widget=_ClearableFileInput())
        f.filesub = None
        if fieldsubmission:
            file_sub = fieldsubmission.file_sub()
            if file_sub:
                f.filesub = file_sub
                f.initial = file_sub.file_attachment
                f.initial.file_sub = fieldsubmission.file_sub()
        return f 
Example 7
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 8
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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
        if callable(upload_to):
            self.generate_filename = upload_to

        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(FileField, self).__init__(verbose_name, name, **kwargs) 
Example 9
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(FileField, self).check(**kwargs)
        errors.extend(self._check_unique())
        errors.extend(self._check_primary_key())
        return errors 
Example 10
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(FileField, self).deconstruct()
        if kwargs.get("max_length", None) == 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 11
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "FileField" 
Example 12
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 13
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 14
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 15
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 16
Project: GTDWeb   Author: lanbing510   File: files.py    License: GNU General Public License v2.0 5 votes vote down vote up
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
Project: bioforum   Author: reBiocoder   File: files.py    License: MIT License 5 votes vote down vote up
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 18
Project: bioforum   Author: reBiocoder   File: files.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "FileField" 
Example 19
Project: bioforum   Author: reBiocoder   File: files.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 20
Project: bioforum   Author: reBiocoder   File: files.py    License: MIT License 5 votes vote down vote up
def __set__(self, instance, value):
        previous_file = instance.__dict__.get(self.field.name)
        super().__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 21
Project: cadasta-platform   Author: Cadasta   File: filters.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def field_value(field):
    """Return the value for this BoundField."""
    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 callable(val):
            val = val()
    if val is None:
        val = ''
    return val 
Example 22
Project: django-localized-fields   Author: SectorLabs   File: test_file_field.py    License: MIT License 5 votes vote down vote up
def test_file_methods(cls):
        """Tests whether the :see:LocalizedFieldFile.delete method works
        correctly."""

        temp_file = File(tempfile.NamedTemporaryFile())
        instance = cls.FileFieldModel()
        # Calling delete on an unset FileField should not call the file deletion
        # process, but fail silently
        instance.file.en.delete()
        instance.file.en.save("testfilename", temp_file)
        assert instance.file.en.name == "testfilename"
        instance.file.en.delete()
        assert instance.file.en.name is None 
Example 23
Project: django-localized-fields   Author: SectorLabs   File: test_file_field.py    License: MIT License 5 votes vote down vote up
def test_formfield():
        """Tests whether the :see:formfield function correctly returns a valid
        form."""

        form_field = LocalizedFileField().formfield()
        assert isinstance(form_field, LocalizedFileFieldForm)
        assert isinstance(form_field, forms.FileField)
        assert isinstance(form_field.widget, LocalizedFileWidget) 
Example 24
Project: dirigible-spreadsheet   Author: pythonanywhere   File: test_forms.py    License: MIT License 5 votes vote down vote up
def test_initialisation(self):
        import_form = ImportCSVForm()
        self.assertTrue(all(map(lambda args : isinstance(*args),[
            (import_form.fields['column'], forms.IntegerField),
            (import_form.fields['row'], forms.IntegerField),
            (import_form.fields['file'], forms.FileField)]))) 
Example 25
Project: django-djangui   Author: Chris7   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        post = request.POST.copy()
        user = request.user if request.user.is_authenticated() else None
        if not djangui_settings.DJANGUI_ALLOW_ANONYMOUS and user is None:
            return JsonResponse({'valid': False, 'errors': {'__all__': [force_text(_('You are not permitted to access this script.'))]}})
        form = utils.get_master_form(pk=post['djangui_type'])
        # TODO: Check with people who know more if there's a smarter way to do this
        utils.validate_form(form=form, data=post, files=request.FILES)
        # for cloned jobs, we don't have the files in input fields, they'll be in a list like ['', filename]
        # This will cause issues.
        to_delete = []
        for i in post:
            if isinstance(form.fields.get(i), FileField):
                # if we have a value set, reassert this
                new_value = post.get(i)
                if i not in request.FILES and (i not in form.cleaned_data or (not form.cleaned_data[i] and new_value)):
                    # this is a previously set field, so a cloned job
                    if new_value is not None:
                        form.cleaned_data[i] = utils.get_storage(local=False).open(new_value)
                    to_delete.append(i)
        for i in to_delete:
            if i in form.errors:
                del form.errors[i]

        if not form.errors:
            # data = form.cleaned_data
            script_pk = form.cleaned_data.get('djangui_type')
            script = Script.objects.get(pk=script_pk)
            valid = utils.valid_user(script, request.user).get('valid')
            if valid is True:
                group_valid = utils.valid_user(script.script_group, request.user).get('valid')
                if valid is True and group_valid is True:
                    job = utils.create_djangui_job(script_pk=script_pk, user=user, data=form.cleaned_data)
                    job.submit_to_celery()
                    return JsonResponse({'valid': True})
            return JsonResponse({'valid': False, 'errors': {'__all__': [force_text(_('You are not permitted to access this script.'))]}})
        return JsonResponse({'valid': False, 'errors': form.errors}) 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: files.py    License: MIT License 5 votes vote down vote up
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 27
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: files.py    License: MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "FileField" 
Example 28
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: files.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        return super().formfield(**{
            'form_class': forms.FileField,
            'max_length': self.max_length,
            **kwargs,
        }) 
Example 29
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: files.py    License: MIT License 5 votes vote down vote up
def __set__(self, instance, value):
        previous_file = instance.__dict__.get(self.field.name)
        super().__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 30
Project: wagtailstreamforms   Author: labd   File: test_fields.py    License: MIT License 5 votes vote down vote up
def test_singlefile_field(self):
        data = self.get_form_field_data("singlefile")
        cls = wsf_fields.SingleFileField()
        field = cls.get_formfield(data)

        self.assertIsInstance(field, forms.FileField)
        self.assertIsInstance(field.widget, forms.widgets.FileInput)
        self.assertEqual(field.label, data["label"])
        self.assertEqual(field.required, data["required"])
        self.assertEqual(field.help_text, data["help_text"])