【问题标题】:How to use the form values inside form_valid function in django如何在 django 中使用 form_valid 函数中的表单值
【发布时间】:2021-07-05 05:05:12
【问题描述】:

我想知道如何在我的视图中将输入的值使用到 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)

form.instance.weekday.all() 中的weekday 是表单中链接到另一个模型的多对多字段。问题是我需要单击更新按钮两次才能使用来自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>]>

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

希望大家帮我把“Tuesday”和“Thursday”(新更改的值)出现在我的form_valid函数中,这样我就不用更新两次了。谢谢,如果您需要任何其他信息,请告诉我。

【问题讨论】:

  • 试试self.cleaned_data,是你想要的吗?
  • 你能告诉我具体方法吗?

标签: django django-models django-views django-forms django-queryset


【解决方案1】:

您可以通过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找到。

【讨论】:

猜你喜欢
  • 2020-08-12
  • 2012-09-09
  • 2015-02-22
  • 1970-01-01
  • 2021-09-22
  • 2017-01-24
  • 1970-01-01
  • 2014-05-04
  • 2016-04-30
相关资源
最近更新 更多