如何在 Django 中使用 form_valid 函数中的表单值

How to use the form values inside form_valid function in django

我想知道在我看来如何将输入的值用于 form_valid 函数中的表单。首先,这是视图:

class OrganisorStudentUpdateView(OrganisorAndLoginRequiredMixin, generic.UpdateView):
    # some code
    form_class = OrganisorStudentUpdateModelForm
    # some code

    def form_valid(self, form, *args, **kwargs):
        # some variables from form

        print(form.instance.weekday.all())

        # some extra mathematical code using the values of form.instance.weekday.all()
        # update some of the other form fields

        print(form.instance.weekday.all())
        return super().form_valid(form, *args, **kwargs)

weekday in form.instance.weekday.all() 是链接到另一个模型的表单中的多对多字段。问题是我需要单击更新按钮两次才能使用 weekday 中的值执行数学代码。这是一个简单的例子。 weekday 表单字段的当前值是选中“星期一”、“星期三”、“星期五”复选框。当我更新表单而不做任何更改时,将打印以下内容:

<QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]>
<QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]>

然后,我会将 weekday 的值更改为“星期二”和“星期四”。我更新了。我明白了:

<QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]>
<QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]>

如您所见,这不是我想要的。我希望星期二和星期四出现。但是,只有当我再次更新此表单时才会发生这种情况:

<QuerySet [<Weekday: Tuesday>, <Weekday: Thursday>]>
<QuerySet [<Weekday: Tuesday>, <Weekday: Thursday>]>

这也意味着当我点击更新按钮两次时,我所有的数学代码都有效(并因此更新了表单字段的其他部分)。

我希望你们能帮我让“星期二”和“星期四”(新更改的值)出现在我的form_valid函数中,这样我就不用更新两次了。谢谢,如果您需要任何其他信息,请告诉我。

您可以通过 form.cleaned_data 方法访问这些值:

def form_valid(self, form, *args, **kwargs):
    # some variables from form

    print(form.cleaned_data)

    # some extra mathematical code using the values of form.instance.weekday.all()
    # update some of the other form fields

    print(form.instance.weekday.all())
    return super().form_valid(form, *args, **kwargs)

但是最好将这些代码放在表单的代码中。例如:

class OrganisorStudentUpdateModelForm(forms.ModelForm):
    ...

    def clean_weekday(self):  # assuming you have a field weekday
      # otherwise use 'clean()' method.
      weekday = self.cleaned_data.get('weekday')
      # do some calculation
      return weekday

可以在 documentation 中找到更多信息。