【问题标题】:Save file from ModelForm's FileField从 ModelForm 的 FileField 中保存文件
【发布时间】:2014-08-26 19:05:19
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 您看过文档中涉及forms and files 的部分吗?您需要确保表单在 html 中是多部分的:<form enctype="multipart/form-data" method="post" action="/foo/">,并且视图中表单的实例化正在获取请求的两个部分:f = ContactFormWithMugshot(request.POST, request.FILES。没有它,表单可能无法将文件传递给视图。
  • 更多here
  • @MBrizzle 这不是我放入网站某些页面的表格。这是在“管理面板”中创建模型的一种形式(正如我在问题中所述)。所以不是这样的
  • 在管理系统中工作不会阻止您访问请求信息。所有管理视图都是完全可扩展的,允许您访问请求:docs.djangoproject.com/en/1.6/ref/contrib/admin/#other-methods。模板也是如此 - 只需覆盖您应用中的 change_form.html 模板。

标签: django django-forms django-admin


【解决方案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

【讨论】:

  • 谢谢,阿列克谢。效果很好。您能否添加指向特定文档文章的链接,每个人都可以阅读此文章?
  • 我只是通过浏览 django 的源代码找到了解决方案,所以我不确定它是否记录在任何地方。不过,我很高兴它对您有所帮助。
【解决方案2】:

您可以调用 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}} 文件夹中

【讨论】:

  • 当我尝试使用 tests_zip_file = tests_zip_field.open() 时,我得到一个异常说“没有全局测试_zip_field”。如果我像这样tests_zip_file = self.tests_zip_field.open() 使用它,那么我会得到一个异常'self doesn't have an object tests_zip_field'(类似这样)。所以它对我不起作用。
  • 它的self.tests_zip_field.open(),你用的是哪个版本的django?
  • 我正在使用 Django v1.6.6
  • 您必须设置 upload_to 才能使其正常工作,请查看docs.djangoproject.com/en/1.6/ref/models/fields/…
猜你喜欢
  • 1970-01-01
  • 2011-08-15
  • 2023-03-30
  • 1970-01-01
  • 2013-04-09
  • 2012-10-14
  • 2021-04-25
  • 2012-05-23
  • 2013-06-25
相关资源
最近更新 更多