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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With