-->

我怎样才能改变形式,我传递给inlineformset_factory中的一个字段的查询集(How

2019-10-17 15:04发布

我使用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()

Answer 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())


文章来源: How can I change the queryset of one of the fields in the form I'm passing to inlineformset_factory