Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file from ModelForm's FileField

I'm trying to upload file using the file input in the model creation page in the Django's admin panel. The file isn't a part of an object, so it doesn't belong to an object itself. I just need to get it, process it and then delete it.

I've created a form:

class AddTaskAndTestsForm(forms.ModelForm):
    tests_zip_field = forms.FileField(required=False)

    def save(self, commit=True):
        # I need to save and process the tests_zip_field file here
        return super(AddTaskAndTestsForm, self).save(commit=commit)

    class Meta:
        model = Problem

And I added the form to the admin panel, so it's now displayed there.

I need to save the file, once the create form is submitted, but how do I do that?

UPDATE: here's how I use it.

admin.py:

class ProblemAdmin(admin.ModelAdmin):
    form = AddTaskAndTestsForm

    fieldsets = [
        # ... some fieldsets here
        ('ZIP with tests', {
            'fields': ['tests_zip_field']
        })
    ]

    # ... some inlines here
like image 965
Vyacheslav Pukhanov Avatar asked Oct 18 '25 13:10

Vyacheslav Pukhanov


2 Answers

Try this:

class AddTaskAndTestsForm(forms.ModelForm):
    tests_zip_field = forms.FileField(required=False)

    def save(self, commit=True):
        instance = super(AddTaskAndTestsForm, self).save(commit=False)
        f = self['tests_zip_field'].value() # actual file object
        # process the file in a way you need
        if commit:
            instance.save()
        return instance
like image 84
lehins Avatar answered Oct 21 '25 00:10

lehins


You can call tests_zip_field.open() ( behaves pretty much like the python open() ) and use it in your save() method like this :

tests_zip_file = self.tests_zip_field.open()
tests_zip_data = tests_zip_file.read()
## process tests_zip_data 
tests_zip_file.close()

the file is saved in your MEDIA_ROOT/{{upload_to}} folder whenever the save() method finishes

like image 28
Shivansh Avatar answered Oct 20 '25 22:10

Shivansh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!