简体   繁体   English

如何访问Django Forms.FileField文件(*不是models.FileField *)?

[英]How to access the Django forms.FileField file (*not models.FileField*)?

I'm running Django 1.7. 我正在运行Django 1.7。

I have the following model form: 我有以下模型形式:

class DeckCreateForm(forms.ModelForm):
    csv_file = forms.FileField(required=False)
    class Meta:
        model = Deck
        fields = ['title', 'description']

Notice that the file field is not part of the model (and I would like to keep it this way). 请注意,文件字段不是模型的一部分(我想保持这种方式)。 This file field is meant to provide an alternative means of constructing the model Deck. 该文件字段旨在提供一种构建Deck模型的替代方法。

I would like to know how to access the uploaded file. 我想知道如何访问上传的文件。 I looked in my media directory but it is not there. 我查看了我的媒体目录,但它不存在。 I tried adding a "upload_to" to the csv_file constructor but get an error: 我尝试在csv_file构造函数中添加“ upload_to”,但出现错误:

TypeError: __init__() got an unexpected keyword argument 'upload_to'

EDIT: 编辑:

I would like to know how to get this to work with a generic class based create view which makes use of the above model form - in views.py I have: 我想知道如何将其与基于通用类的create视图一起使用,该视图使用上述模型形式-在views.py中,我有:

class DeckCreateView(CreateView):
    model = Deck
    form_class = DeckCreateForm
    template_name = 'deck_create.html'

Specifically, how do I modify something like http://docs.djangoproject.com/en/1.7/topics/http/file-uploads to work with the above class based view. 具体来说,如何修改类似http://docs.djangoproject.com/zh-CN/1.7/topics/http/file-uploads之类的内容,才能与上述基于类的视图一起使用。 My urls.py file: 我的urls.py文件:

urlpatterns = patterns(
    ...
    url(r"^deck/create/$", views.DeckCreateView.as_view(), name="deck-create"),
    ...
)

Is there a method which I can override in DeckCreateView to handle the file upload? 有没有可以在DeckCreateView中覆盖的方法来处理文件上传?

I've found that the Django documentation concerning file uploads can be a little difficult to understand for newer Django users. 我发现对于较新的Django用户而言,有关文件上传的Django文档可能有点难以理解。 However, I think that the following link provides a very concise and easy to follow step by step process of setting up a file upload form. 但是,我认为以下链接提供了一个非常简洁且易于遵循的逐步步骤,以建立文件上传表单。

Need a minimal Django file upload example 需要一个最小的Django文件上传示例

I believe you'll find everything you need there. 我相信您会在那里找到所需的一切。

Edit 编辑

In response to the OP's edit and comment concerning class based views, I believe they can be clearer and arguably "cleaner" looking code than function based views. 作为对OP关于基于类的视图的编辑和评论的回应,我相信它们比基于函数的视图更清晰,可以说是“更干净”的代码。 Here is a great link discussing CBV and FBV that includes a simple, but effective example of CBV. 这是讨论CBV和FBV的重要链接,其中包括一个简单但有效的CBV示例。

http://www.datalifebalance.com/2014/04/django-file-uploads-with-class-based-views.html http://www.datalifebalance.com/2014/04/django-file-uploads-with-class-based-views.html

Addendum to Edit 附录进行编辑

For the sake of completeness, and to limit the dependence of the answer on the above external link (which may disappear one day), we add a few more details. 为了完整起见,并为了限制答案对上述外部链接的依赖(可能会在一天内消失),我们添加了更多详细信息。 In order to achieve their objective, the OP could override the post method of DeckCreateView and save, __init__ of DeckCreateForm like so: 为了实现其目标,OP可以重写DeckCreateView的post方法并保存DeckCreateForm的__init__,如下所示:

views.py: views.py:

...

class DeckCreateView(CreateView):
    ...
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(self.success_url)
        else:
            return render(request, self.template_name, {'form': form})

forms.py forms.py

...

class DeckCreateForm(forms.ModelForm):
    ...
    def __init__(self, post_data, files_data):
        self.csv_file = files_data.get('csv_file', None)
        return super(DeckCreateForm, self).__init__(post_data, files_data)

    def save(self, *args, **kwargs):
        deck = super(DeckCreateForm, self).save(*args, **kwargs)
        self.handle_csv_file(self.csv_file, deck)
        return deck

    def handle_csv_file(f, deck):
        ...
        for chunk in f.chunks():
            ... 
        ...

Upon form submission a request is sent to DeckCreateView::post. 表单提交后,请求将发送到DeckCreateView :: post。 The file handling occurs when DeckCreateForm::save is called. 当调用DeckCreateForm :: save时发生文件处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django:访问models.filefield(upload_to)位置中的主键 - Django: Access primary key in models.filefield(upload_to) location Django:如何将字节 object 保存到 models.FileField? - Django: how save bytes object to models.FileField? Django-inspectdb-“ models.FileField”显示为“ models.CharField” - Django - inspectdb - the “models.FileField” are displayed as “models.CharField” 告诉我使用Django模型的方法。 - Tell me the way to use Django's models.FileField 添加自定义文件名 django model (models.FileField) - Add custom filename django model (models.FileField) Django models.FileField-仅存储文件名,不存储任何路径或文件夹引用 - Django models.FileField - store only the file name not any paths or folder references Django 音乐播放器:按下播放按钮时,models.FileField 未正确将音频文件传递给 HTML - Django music player: models.FileField not properly passing audio file to HTML when Play button is pressed 如何使用models.FileField将文件保存在数据库中而不是上传到服务器媒体文件夹中? - How to Save file in database instead of upload in server media folder ,using models.FileField? 如何动态选择models.FileField的存储选项? - How to dynamically select storage option for models.FileField? 将“str”放入 Djano forms.FileField() - Get 'str' into Djano forms.FileField()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM