具有现有数据的form和ModelMultipleChoiceField

时间:2017-05-10 22:56:01

标签: django forms django-forms django-views

This post对此主题非常有帮助。但是,我正在使用基于类的视图,并且想知道如何完成添加" selected"当查询集依赖于我正在使用的模型的实例时,项目到ModelMultipleChoiceField。

型号:

class OfferGroup(models.Model):
    name = models.CharField(max_length=64, null=False)
    priority = models.IntegerField(null=False, unique=True)

    class Meta:
        verbose_name = _('OfferGroup')
        ordering = ['priority', ]


class ConditionalOffer(AbstractConditionalOffer):
    groups = models.ManyToManyField('auth.Group', verbose_name=_("User Groups"), blank=True)
    offer_group = models.ForeignKey(OfferGroup, related_name='offers', null=True)
    ...
    class Meta:
        ordering = ['priority', ]

其中AbstractConditionalOffer提供字段" name',' offer_type',开始和结束日期时间以及其他模型的外键。

形式:

class OfferGroupForm(forms.ModelForm):
    offers = ModelMultipleChoiceField(queryset=ConditionalOffer.objects.all(),
        widget=forms.widgets.SelectMultiple(), required=False)

class Meta:
    model = OfferGroup
    fields = ('name', 'priority', 'offers')

这个表格并不是我真正需要的,见下文

查看:

class OfferGroupUpdateView(UpdateView):
    model = OfferGroup
    template_name = 'dashboard/offers/offergroup_edit.html'
    form_class = OfferGroupForm
    success_url = reverse_lazy('dashboard:offergroup-list')

    def save_offers(self, offer_group, form):
        selected_offers = form.cleaned_data['selected']
        for offer in selected_offers:
            offer_group.offers.add(offer, bulk=False)
        other_offers = form.cleaned_data['not_selected']
        for offer in other_offers & offer_group.offers.all():
            offer_group.offers.remove(offer)
        form.save()
        return HttpResponseRedirect(reverse('dashboard:offergroup-list'))

    def form_valid(self, form):
        offer_group = form.save(commit=False)
        return self.save_offers(offer_group, form)

现在,这种方法的问题在于,提供给OfferGroupForm的查询集并未提供有关所选商品的任何信息以及我想要编辑的OfferGroup实例的优惠信息:< / p>

我需要的是类似

og = OfferGroup.objects.get(pk=current offer_groups primary key)
selected = ConditionalOffers.objects.filter(offer_group=og)
other = ConditionalOffers.objects.exclude(offer_group=og)

因此,在呈现视图时,具有当前要约组(正在编辑的要约组)的外键的商品显示为已选择

此外,有没有办法在使用模型表单的基于类的视图中执行此操作?

请原谅我,如果我提供的代码有点模糊 - 我试图展示最显着的片段。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

解决方案是覆盖视图中的get_context_data方法:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # get the current obj
    obj = context.get('offergroup')
    # use the current object to get related objects
    qs = ConditionalOffer.objects.filter(offer_group=obj)
    # add context variables that can be used in the template
    context['selected'] = qs.values_list('name', flat=True)
    context['offers'] = ConditionalOffer.objects.all().exclude(offer_group=obj)
    return context
相关问题