【问题标题】:How can I change the queryset of one of the fields in the form I'm passing to inlineformset_factory如何更改要传递给 inlineformset_factory 的表单中某个字段的查询集
【发布时间】:2013-01-24 11:54:49
【问题描述】:

我正在使用 django 额外视图:

# views.py
from django.forms.models import inlineformset_factory
from extra_views import (CreateWithInlinesView, UpdateWithInlinesView,
                        InlineFormSet, )

class LinkInline(InlineFormSet):
    model = Link
    form = LinkForm
    extra = 1

    def get_form(self):
        return LinkForm({})

    def get_formset(self):
        return inlineformset_factory(self.model, self.get_inline_model(), form=LinkForm, **self.get_factory_kwargs())

class TargetCreateView(BaseSingleClient, CreateWithInlinesView):
    model = Target
    form_class = TargetForm
    inlines = [LinkInline, ]
    template_name = 'clients/target_form.html'

我希望这个“关键字”字段根据我通过 url 传递给视图的 pk 进行更改。

# forms.py
class LinkForm(forms.ModelForm):
    keywords = forms.ModelMultipleChoiceField(queryset=ClientKeyword.objects.filter(client__pk=1))

    class Meta:
        model = Link

我可以设法覆盖表单的 init,但是:

  1. 我无法访问 LinkInline 中的 self.kwargs

  2. 即使我这样做了,我也不确定是否可以将实例化的表单传递给 inlineformset_factory()

【问题讨论】:

  • 既然提前有pk,有没有考虑过用curry把pk传给form?
  • 我将代码添加到我如何在答案中做到这一点,但我很感兴趣......甚至不知道什么是咖喱
  • 当我需要将值传递给我在表单集中使用的表单时,我使用 curry:from django.utils.functional import curryMyFormset.form = staticmethod(curry(MyForm, pk=pk)) 表单在此示例中,需要接受 pk 的 kwarg。
  • 哦,...类似这样的:stackoverflow.com/questions/622982/…。问题是我只能从 TargetCreateView 中获取 pk。如果我在 LinkInline 中有它,我也许可以从 get_formset() 返回 inlineformset_factory(self.model, self.get_inline_model(), form=curry(LinkForm, pk=pk), **self.get_factory_kwargs()),但由于它不存在,我不知道它是如何工作的
  • 仅供参考,Extra Views 内置了 currying 技巧(请参阅这些行:github.com/AndrewIngram/django-extra-views/blob/master/…),所以问题只是没有将视图 kwargs 传递给内联,这应该是介绍比较简单。我只需要确保没有讨厌的向后兼容性问题。我也可以传递视图对象,因此您不必重做已在视图中处理的任何工作。

标签: django django-views inline-formset


【解决方案1】:

好的,如果有任何可怜的灵魂需要回答如何完成此任务...我设法通过覆盖construct_inlines()(它是extra_views.advanced.ModelFormWithInlinesMixin 的一部分)并在那里修改该字段的查询集来做到这一点。

class TargetCreateView(BaseSingleClient, CreateWithInlinesView):
    model = Target
    form_class = TargetForm
    inlines = [LinkInline, ]
    template_name = 'clients/target_form.html'

    def construct_inlines(self):
        '''I need to overwrite this method in order to change
        the queryset for the "keywords" field'''
        inline_formsets = super(TargetCreateView, self).construct_inlines()
        inline_formsets[0].forms[0].fields[
                'keywords'].queryset = ClientKeyword.objects.filter(
                        client__pk=self.kwargs['pk'])
        return inline_formsets

    def forms_valid(self, form, inlines):
        context_data = self.get_context_data()
        # We need the client instance
        client = context_data['client_obj']
        # And the cleaned_data from the form
        data = form.cleaned_data
        self.object = self.model(
                client=client,
                budget=data['budget'],
                month=data['month']
        )
        self.object.save()
        for formset in inlines:
            f_cd = formset.cleaned_data[0]
            print self.object.pk
            link = Link(client=client,
                    target=self.object,
                    link_type=f_cd['link_type'],
                    month=self.object.month,
                    status='PEN',
            )
            # save the object so we can add the M2M fields
            link.save()
            for kw in f_cd['keywords'].all():
                link.keywords.add(kw)
        return HttpResponseRedirect(self.get_success_url())

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 2020-09-05
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多