Django表单模型multiplechoicefield

时间:2019-08-21 14:42:51

标签: django django-forms django-views

我过滤并列出了匹配项,但是当我尝试选择和添加匹配项时,不会添加我选择的匹配项。

views.py

def creategame(request,tournamentslug):


    form=GameForm(request.POST or None)
    tournament = get_object_or_404(Tournament, slug=tournamentslug)

     form.fields["match"]=forms.ModelMultipleChoiceField(widget=forms.SelectMultiple(attrs={'class':'matchc'}),required=False,queryset=Match.objects.filter(name__icontains=tournament.name))

if form.is_valid():
    game = form.save(commit=False)
    #game have more than 1 fields such name,date.. and more
    """
    fields=['name',
            'date',...
            ]
    """
    game.tournament=tournament
    game.save()
    return HttpResponseRedirect(game.get_absolute_url())

html

              <div class="form-item">
                <label for="id_match" class="rl-label" style="margin-bottom: 10px;">Match:</label>
                  {{ form.match }}
              </div>

1 个答案:

答案 0 :(得分:0)

我在下面的game.save()代码下添加了它,并且有效

form.save_m2m()