1

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

4

1 回答 1

3

好的,如果有任何可怜的灵魂需要回答如何实现这一点......我设法通过覆盖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-01-24T15:36:08.160 回答