&#34;选择有效的选择。 <choice>不是可用的选择之一&#34;提交ManyToMany ModelForm时出错

时间:2015-08-14 19:17:27

标签: django django-models django-forms modelform manytomanyfield

我想将ManyToManyField的选择限制为与ForeignKey匹配的选项。表单正确显示,但在保存结果时出现错误&#34;选择有效选项。不是可用的选择之一&#34;。

在我尝试通过将视图中的参数传递给表单来限制查询集之前,然后使用该参数来过滤查询集。

型号:

class VenueEventTimeslot(models.Model):
    venue = models.ForeignKey(Venue)
    name = models.CharField(max_length=255)

class VenueEvent(models.Model):
    venue = models.ForeignKey(Venue)
    event_timeslots = models.ManyToManyField(VenueEventTimeslot)    

class VenueEventForm(ModelForm):
    event_timeslots = ModelMultipleChoiceField(queryset=None, widget=CheckboxSelectMultiple())

    def __init__(self, *args, **kwargs): # limit timeslots to those of the venue only
        venue_obj = kwargs.pop('venue_obj',None)
        super(VenueEventForm, self).__init__(*args,**kwargs)
        self.fields['event_timeslots'].queryset=VenueEventTimeslot.objects.filter(venue=venue_obj)

    class Meta:
        model = VenueEvent
        fields = ['event_timeslots']

查看:

@login_required
def calendar(request, pk):
    venue = Venue.objects.get(pk = pk)

    if request.method == "POST":
        form = VenueEventForm(request.POST)
        if form.is_valid():
            # form stuff
        else:
            form = VenueEventForm(venue_obj = venue)

    context = {'venue':venue, 'form':form}
    return render(request, ... , context)

但是,如果我从视图中传递了查询集,它就能完美运行。

型号:

class VenueEventTimeslot(models.Model):
    # same as above

class VenueEvent(models.Model):
    # same as above 

class VenueEventForm(ModelForm):
    class Meta:
    model = VenueEvent
    fields = ['date','client_name','event_timeslots']
    widgets = {
        'date': SelectDateWidget(),
        'event_timeslots': CheckboxSelectMultiple(),
    }

查看:

@login_required
def calendar(request, pk):
    venue = Venue.objects.get(pk = pk)

    if request.method == "POST":
        form = VenueEventForm(request.POST)
        if form.is_valid():
            # form stuff
        else:
            form = VenueEventForm()
    form.fields['event_timeslots'].queryset=VenueEventTimeslot.objects.filter(venue=venue)

    context = {'venue':venue, 'form':form}
    return render(request, ..., context)

有人能够对此有所了解吗?

1 个答案:

答案 0 :(得分:1)

我刚刚解决了类似于昨天的问题,就在这里,How To Exclude A Value In A ModelMultipleChoiceField?,但我认为你的init函数的问题是它的格式化方式。而不是venue = venue_obj,你需要将它改为pk = venue_obj,因为看起来你在视图中获得了场地的pk而不是VenueEvent的场地属性,我重新格式化了你的表格以使它看起来更干净。 / p>

forms.py

class VenueEventForm(ModelForm):

    def __init__(self, *args, **kwargs): # limit timeslots to those of the venue only
        venue_obj = kwargs.pop('venue_obj')
        super(VenueEventForm, self).__init__(*args,**kwargs)
        self.fields['event_timeslots'] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=VenueEventTimeslot.objects.filter(pk=venue_obj))

    class Meta:
        model = VenueEvent
        fields = ['event_timeslots']

views.py

@login_required
def calendar(request, pk):
    venue = Venue.objects.get(pk = pk)
    if request.method == "POST":
        form = VenueEventForm(request.POST, venue_obj=venue)
        if form.is_valid():
            # form stuff
        else:
            print VenueEventForm.errors

    else:
        form = VenueEventForm(venue_obj=venue)
        context = {'venue':venue, 'form':form}
        return render(request, ... , context)