在内联表单集中使用 Django FileField

2024-01-16

在我的应用程序中上传文件时遇到问题。用户提交报告并可以添加附件(通过外键关系)。我已经显示了内联表单,如果我将其留空,它就会工作,但是当我尝试上传文件然后提交表单时,我收到 500 错误。基本报告已制作,但内联的附件未保存。

forms.py

class ReportForm(forms.ModelForm):
    accidentDate = forms.DateField(widget=SelectDateWidget(
                                   empty_label=("Choose Year",
                                                 "Choose Month",
                                                 "Choose Day"),
                                   ),
                                   label=(u'Accident Date'),
                                   initial=timezone.now())
    claimNumber = forms.CharField(max_length=50,
                                  label=(u'Claim Number'),
                                  required=True)
    damageEstimate = forms.DecimalField(max_digits=6, decimal_places=2,
                                        label=(u'Damage Estimate'))


    description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5,
                                                               'cols': 80}
                                                        ),
                                  label=(u'Description'),
                                  required=True)
    drivable = forms.BooleanField(label=(u'Drivable'), 
                                  required=False)
    receivedCheck = forms.CharField(max_length=30, label=(u'Who Received Check'))
    reported = forms.BooleanField(label=(u'Reported to Insurance Company'), 
                                  required=False)
    reportedDate = forms.DateField(widget=SelectDateWidget(
                                    empty_label=("Choose Year",
                                                 "Choose Month",
                                                 "Choose Day"),
                                ),
                               initial=timezone.now(),
                               label=(u'Date Reported to Insurance'))
    repairsScheduled = forms.DateField(widget=SelectDateWidget(
                                    empty_label=("Choose Year",
                                                 "Choose Month",
                                                 "Choose Day"),
                                ),
                               initial=timezone.now(),
                               label=(u'Scheduled Repair Date'))
    repairsCompleted = forms.DateField(widget=SelectDateWidget(
                                    empty_label=("Choose Year",
                                                 "Choose Month",
                                                 "Choose Day"),
                                ),
                               initial=timezone.now(),
                               label=(u'Repair Completion Date'))
    repairsPaid = forms.BooleanField(label=(u'Repairs Paid'), 
                                  required=False)
    subrogationReceived = forms.BooleanField(label=(u'Subrogation Received'), 
                                  required=False)
    subrogationDate = forms.DateField(widget=SelectDateWidget(
                                    empty_label=("Choose Year",
                                                 "Choose Month",
                                                 "Choose Day"),
                                ),
                               initial=timezone.now(),
                               label=('Subrogation Date'))

class Meta:
    model = Report
    exclude = ('driver',)


ReportAttachmentFormSet = inlineformset_factory(Report,  # parent form
                                                    ReportAttachment,  # inline-form
                                                    fields=['title', 'attachment'], # inline-form fields
                                                    # labels for the fields
                                                    labels={
                                                        'title': (u'Attachment Name'),
                                                        'attachment': (u'File'),
                                                    },
                                                    # help texts for the fields
                                                    help_texts={
                                                        'title': None,
                                                        'attachment': None,
                                                    },
                                                    # set to false because cant' delete an non-exsitant instance
                                                    can_delete=False,
                                                    # how many inline-forms are sent to the template by default
                                                    extra=1)

相关views.py CreateView

class ReportCreateView(CreateView):
    model = Report
    form_class = ReportForm
    object = None

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates blank versions of the form
        and its inline formsets.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        report_attachment_form = ReportAttachmentFormSet()
        return self.render_to_response(
                  self.get_context_data(form=form,
                                        report_attachment_form=report_attachment_form,
                                        )
                                     )

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance and its inline
        formsets with the passed POST variables and then checking them for
        validity.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        report_attachment_form = ReportAttachmentFormSet(self.request.POST, self.request.FILES)
        if form.is_valid() and report_attachment_form.is_valid():
            return self.form_valid(form, report_attachment_form)
        else:
            return self.form_invalid(form, report_attachment_form)

    def form_valid(self, form, report_attachment_form):
        """
        Called if all forms are valid. Creates Report instance along with the
        associated ReportAttachment instances then redirects to success url
        Args:
            form: Report Form
            report_attachment_form: Report attachment Form

        Returns: an HttpResponse to success url

        """
        self.object = form.save(commit=False)
        # pre-processing for Report instance here...

        self.object.driver = Profile.objects.get(user=self.request.user)
        self.object.save()

        # saving ReportAttachment Instances
        report_attachments = report_attachment_form.save(commit=False)
        for ra in report_attachments:
            #  change the ReportAttachment instance values here
            #  ra.some_field = some_value
            ra.save()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, report_attachment_form):
        """
        Called if a form is invalid. Re-renders the context data with the
        data-filled forms and errors.

        Args:
            form: Report Form
        report_attachment_form: Report Attachment Form
        """
        return self.render_to_response(
                 self.get_context_data(form=form,
                                       report_attachment_form=report_attachment_form
                                       )
        )

报告表单.html

{% block body %}
<p>
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <fieldset>
            {{ form.non_field_errors }}
            {% for field in form %}
            <div class="row">
                <div class="col-md-3">{% bootstrap_label field.label %}</div>
                <div class="col-md-8">{% bootstrap_field field show_label=False %}</div>
            </div>
            {% endfor %}
    </fieldset>
    <fieldset>
            <legend>Attachments</legend>
            {{ report_attachment_form.management_form }}
            {{ report_attachment_form.non_form_errors }}
                            {% for form in report_attachment_form %}
                    <div class="inline {{ report_attachment_form.prefix }}">
                    {% for field in form.visible_fields %}
                            <div class="row">
                                    <div class="col-md-3">{% bootstrap_label field.label %}</div>
                                    <div class="col-md-8">{% bootstrap_field field show_label=False %}</div>
                            </div>
                    {% endfor %}
                    </div>
            {% endfor %}
    </fieldset>
    <div class="row">
            <div class="col-md-1">
                    <input type="submit" class="btn btn-groppus-primary bordered" value="Submit" />
            </div>
    </div>
    </form>
</p>
{% endblock %}

{% block scripts %}
    <script src="{% static 'formset/jquery.formset.js' %}"></script>
    <script type="text/javascript">
            $(function() {
                    $(".inline.{{ report_attachment_form.prefix }}").formset({
                            prefix: "{{ report_attachment_form.prefix }}", // The form prefix for your django formset
                            addCssClass: "btn btn-block btn-primary bordered inline-form-add", // CSS class applied to the add link
                            deleteCssClass: "btn btn-block btn-primary bordered", // CSS class applied to the delete link
                            addText: 'Add another attachment', // Text for the add link
                            deleteText: 'Remove attachment above', // Text for the delete link
                            formCssClass: 'inline-form' // CSS class applied to each form in a formset
                    })
            });
    </script>
{% endblock %}

很难弄清楚这个问题,因为它没有给我任何类型的回溯来处理,我在表单中包含了 enc 类型,并且在views.py 文件中传递了 request.FILES。我已经以正常形式进行文件上传,但事实证明内联很麻烦。

如果您需要我澄清任何事情,请告诉我,我们将不胜感激:)

更新:通过使用 CreateView csrf 豁免获得回溯@method_decorator(csrf_exempt, name='dispatch')

which gives me a ValueError: save() prohibited to prevent data loss due to unsaved related object 'report'. From the trace I can see that my file is in fact making it into memory, and the issue is here:traceback

随着我的进步,我将继续更新,似乎这种保存 FK 对象的方法在 1.8 之前工作得非常完美,所以如果我幸运的话,这是一个快速修复以正确保存对象。


我所需要做的就是将我正在使用的报告表单实例传递给表单集,既简单又方便。所以在我的CreateView的post方法中,我将report_attachment_form的声明更改为report_attachment_form = ReportAttachmentFormSet(self.request.POST, self.request.FILES, instance=form.instance)我们就像金子一样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在内联表单集中使用 Django FileField 的相关文章

随机推荐

  • 为Android编译imagemagick

    我正在尝试编译这个项目https github com lilac Android ImageMagick https github com lilac Android ImageMagick 要生成 android magick so 我
  • 单色黑白位图

    我正在 Android 上工作 将从相机捕获的彩色位图转换为黑白单色图像 没有灰色 我有几种灰度转换方法 但我无法将图像转换为黑白格式 有没有什么方法可以将位图转换成这种格式 一种可靠的方法是平均阈值位图 该方法描述于这张纸 http ww
  • 迭代 HashSet 最快/最安全的方法是什么?

    我对 C 还很陌生 但通过论坛帖子注意到使用HashSet代替List在特定情况下 我当前的情况并不是将大量数据存储在单个List完全正确 但我不必经常检查它的成员 问题是我确实也需要迭代它 但它们存储或检索的顺序实际上并不重要 我已经读到
  • 以编程方式更改 Windows 中的打印机首选项

    我编写了一个为新用户安装多台打印机的脚本 我想更改其中一些设置 以便它们可以在页面的双面打印 我相信这涉及使用 printui 修改属性 但是它可能需要 VB 脚本或可能需要另一种 NET 语言 我会使用 VB C 或 IronPython
  • Axis2 会话管理

    我正在axis2中构建一个小型web服务 自下而上 我编写java类并让eclipse wtp生成服务 我想使用会话 以便用户可以使用用户名登录并通过 如果数据库中存在该用户名 而不是在会话上下文中使用 Web 服务 坦白说 我不知道从哪里
  • loader 和 AsyncTask 有什么区别? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我想知道 Android loader 和 AsyncTask 之间的区别 这是 Loader 上的演示 package com android
  • 处理 Datomic 中存储的无序消息?

    背景 在分布式系统中 消息可能会以无序的方式到达 例如 如果消息 A 在时间 T1 发送 消息 B 在时间 T2 发送 则有可能在 A 之前接收到 B 例如 如果 A 是诸如 CustomerRegistered 的消息而 B 是 Cust
  • iOS7 中奇怪的 UITabBar 颜色不一致

    我使用的是 iOS 7tintColor and barTintColor属性来为我的颜色着色UITabBar在 UITabBarController 的子类中使用以下代码 UITabBar appearance setBarTintCol
  • 在 OpenJdk 中,如何使用appendedfontpath属性设置字体目录

    我试图让我的应用程序使用 OpenJdk 安装中特定位置的字体附加字体路径财产 但它对我不起作用 jre1 8 0 121 1 bin java Dappendedfontpath usr lib fonts jar lib songkon
  • 当 URL 中不存在可选参数时找不到 Web API 操作

    请帮忙 我必须更改 Web API 的路由才能使用 URL 中的方法 public class RouteConfig public static void RegisterRoutes RouteCollection routes rou
  • 防止引导工具提示在单击时隐藏

    我想防止工具提示在我单击它时隐藏 除了无论我点击 body 时它都应该隐藏它 即使在选项卡上 工具提示也应该起作用 jsfiddle http jsfiddle net C5GBU 41 http jsfiddle net C5GBU 41
  • Blade.php 方法将结果输出到表单

    我目前正在使用 Laravel 4 2 框架和 twitter bootstrap 设计一个网站 我已经设置了我的master blade php文件 在每个页面的顶部显示一个导航栏 基本上 如果用户登录 我想显示一个导航栏 其选项与用户未
  • 如何将一列中的数据分成两列?

    我最近刚刚开始学习 MS Access 和 SQL Server 中的 SQL 所以我的知识非常有限 但我正在寻找有关 MS Access 中查询的帮助 我知道如何将 2 列合并为 1 列 并用逗号或我想要的任何符号分隔最终结果 但是 我该
  • 错误:找不到您尝试购买的商品

    我是一名安卓初学者 我创建了一个测试应用程序 它只有一个按钮 当您单击它时 它会启动应用内购买 几天前还可以用 但现在不行了 我还检查了其他相关帖子 我尝试了所有 测试帐户 和 活动应用内产品 方法 但它仍然给我相同的错误消息 另外 我尝试
  • 有没有办法更改未使用 basicConfig 配置的记录器对象的文件模式?

    如果我使用 logger logging getLogger Name 创建记录器对象 我无法将文件模式从追加 a 更改为写入 w 如果我将根记录器与 basicConfig 一起使用 则可以 但是当我想要的只是从 DEBUG 级别开始的我
  • 根据匹配的行合并两个csv文件并在linux中添加新列

    我正在使用 java 开发一个应用程序 但为此我需要一个按顺序排列的 csv 文件 我对linux不太了解 但想知道是否有某种方法可以将csv文件合并为所需的格式 我有两个 csv 文件 其中包含数十万条记录 示例如下 name Direc
  • 如何列出Qt5的所有CMake组件?

    我知道在 CMake 中我可以找到并需要我需要的 Qt5 库 代码如下 find package Qt5 5 12 0 REQUIRED COMPONENTS Gui Qml QuickControls2 Svg 但我怎么知道我可以在后面列
  • 在 Fabric8 Kubernetes 客户端 events() API 的 Watcher 中,我可以监视哪些资源?

    我正在探索 无证 events API https github com fabric8io kubernetes client blob master kubernetes client src main java io fabric8
  • Qt 中区分单击事件和双击事件

    我有一个QAbstractItemView需要对单击和双击事件做出反应 根据单击还是双击 操作会有所不同 发生的问题是在双击事件之前接收到单击事件 是否有推荐的方法 最佳实践来区分两者 当用户实际双击时 我不想执行单击操作 我正在使用 Qt
  • 在内联表单集中使用 Django FileField

    在我的应用程序中上传文件时遇到问题 用户提交报告并可以添加附件 通过外键关系 我已经显示了内联表单 如果我将其留空 它就会工作 但是当我尝试上传文件然后提交表单时 我收到 500 错误 基本报告已制作 但内联的附件未保存 forms py