从ModelForm的FileField中保存文件

时间:2014-08-26 19:05:20

标签: django django-forms django-admin

我正在尝试使用Django管理面板中模型创建页面中的文件输入来上传文件。该文件不是对象的一部分,因此它不属于对象本身。我只需要得到它,处理它然后删除它。

我创建了一个表单:

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

我将表单添加到管理面板,现在它就显示在那里了。

我需要保存文件,一旦提交了创建表单,但我该怎么做?

更新:以下是我如何使用它。

admin.py

class ProblemAdmin(admin.ModelAdmin):
    form = AddTaskAndTestsForm

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

    # ... some inlines here

2 个答案:

答案 0 :(得分:1)

你可以调用tests_zip_field.open()(表现得非常像python open())并在你的save()方法中使用它,如下所示:

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

每当save()方法完成时,文件都会保存在MEDIA_ROOT / {{upload_to}}文件夹中

答案 1 :(得分:1)

试试这个:

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
相关问题