Django 表单文本字段预填充来自其他表单的数据

Django form text field prefilling with data from other form

我 运行 遇到了一个非常奇怪的问题,即一个表单完全使用另一个表单的数据进行初始化。这是第一个视图:

class UpdateProfileView(FormMixin, DetailView):
    form_class = UpdateProfileForm
    model = Profile
    template_name = 'profile/update.html'

    def get_context_data(self, **kwargs):
        self.object = self.get_object()
        context = super(UpdateProfileView, self).get_context_data(**kwargs)
        ...
        self.initial['description'] = profile.about

        context['form'] = self.get_form()
        return context
    ...

这是将 return 正确数据的表格。但是,一旦加载,以下表单将 return 来自前一个表单的初始化数据,甚至来自不同的会话、浏览器和位置:

class BountyUpdateForm(forms.ModelForm):

    class Meta:
        model = Bounty
        fields = ("description", "banner")


class UpdateBountyView(UpdateView):
    form_class = BountyUpdateForm
    model = Bounty
    template_name = 'bounty/update.html'
    ...

    def get_context_data(self, **kwargs):
        context = super(UpdateBountyView, self).get_context_data(**kwargs)
        description = context['form']['description']
        value = description.value()
        # Value equals what was initialized by the previous form.

我很好奇为什么这两种形式会以这种方式相互作用。两个表单域都称为 'description',但这并不能解释为什么一个的初始数据会交叉到另一个。重新启动服务器似乎暂时让第二种形式显示正确的值,但一旦加载第一个,第二个就会随之而来。

如有任何帮助,我们将不胜感激!

经过更多搜索后,我能够确定我的第二个视图 self.initial 设置为与第一个表单相同的值,而调度时间为 运行。我无法确定原因,但发现了这些相关问题:

同样的问题,但没有被接受的答案: Django(trunk) and class based generic views: one form's initial data appearing in another one's

不同的问题,但很好的答案: Setting initial formfield value from context data in Django class based view

我的解决方法是在我的第一个表单上覆盖 get_initial(),而不是直接设置 self.initial['description']。

class UpdateProfileView(FormMixin, DetailView):
    form_class = UpdateProfileForm
    model = Profile
    template_name = 'profile/update.html'

    def get_initial(self):
        return {
            'description': self.object.about
        }

    def get_context_data(self, **kwargs):
        ...
        # Removed the following line #
        # self.initial['description'] = profile.about
        ...
        context['form'] = self.get_form()
        return context

希望这对 运行 遇到同样问题的其他人有所帮助。我希望我能更多地了解基于 Django class 的视图,以便能够理解为什么会发生这种情况。但是,除了 FormMixin() 中的空字典之外,我无法确定 self.initial 的设置位置。