Django未绑定和绑定的表单

时间:2015-10-23 10:27:34

标签: django django-forms

我正在创建一项服务,人们可以创建指南,包括名为hearthstone的视频游戏的套牌。首先必须选择他们的英雄:

class SelectHero(ListView):
    template_name = 'hsguides/select_hero.html'
    model = Hero

    def get_context_data(self, **kwargs):
        context = super(SelectHero, self).get_context_data(**kwargs)
        context['heroes'] = Hero.objects.all()
        return context

当它被选中时,我用甲板和指南表格渲染一个模板。现在,当我使用此设置时:

查看

@login_required(login_url="/accounts/login")
def guide_create_view(request, hero):
    print(DeckForm)
    return render(request, 'hsguides/guide_create.html', {
        'DeckForm': DeckForm(hero),
        'GuideForm': GuideForm,
    })

形式

class DeckForm(ModelForm):
    class Meta:
        model = Deck
        exclude = ('dust', 'hero',)


    def __init__(self, hero=None, **kwargs):
        super(DeckForm, self).__init__(**kwargs)
        if hero:
            self.fields['weapon_cards'].queryset = Weapon.objects.filter(Q(card_class='neutral') |
                                                                         Q(card_class=hero))
            self.fields['spell_cards'].queryset = Spell.objects.filter(Q(card_class='neutral') |
                                                                       Q(card_class=hero))
            self.fields['minion_cards'].queryset = Minion.objects.filter(Q(card_class='neutral') |
                                                                         Q(card_class=hero))

我看到此表单是未绑定,当我想在保存视图中使用它时它无效

@login_required(login_url="/accounts/login")
def guide_save(request):
    if request.method == "POST":
        deck_form  =  DeckForm(request.POST)
        guide_form = GuideForm(request.POST)
        print(guide_form.is_bound) # printed value, True
        print(deck_form.is_bound) # printed value, False
        if guide_form.is_valid() and deck_form.is_valid():
            new_deck  = deck_form.save(commit=False)
            new_deck.dust = 0 #TODO create a count method for the dust field!
            new_deck.save()

            new_guide = guide_form.save(commit=False)
            new_guide.author = Account.objects.get(id=request.user.id)
            new_guide.deck = Deck.objects.get(id=new_deck.id)
            new_guide.save()
        else:
            print(guide_form.errors)
            print(deck_form.errors)
    else:
        deck_form = DeckForm()
        guide_form = GuideForm()

    return HttpResponseRedirect('/guides/search-guide/')

现在我真的依赖这部分:

def __init__(self, hero=None, **kwargs):
        super(DeckForm, self).__init__(**kwargs)
        if hero:
            self.fields['weapon_cards'].queryset = Weapon.objects.filter(Q(card_class='neutral') |
                                                                         Q(card_class=hero))
            self.fields['spell_cards'].queryset = Spell.objects.filter(Q(card_class='neutral') |
                                                                       Q(card_class=hero))
            self.fields['minion_cards'].queryset = Minion.objects.filter(Q(card_class='neutral') |
                                                                         Q(card_class=hero))

但我不知道如何验证甲板表格并以最佳方式保存。在最佳实践方面,我如何才能最好地处理这种情况?

1 个答案:

答案 0 :(得分:1)

您已重新定义表单的签名,以便第一个参数为hero,但之后只用request.POST实例化它。

而不是这样做,从kwargs中获取hero,并始终确保你接受args和kwargs。

def __init__(self, *args, **kwargs):
    hero = kwargs.pop('hero', None)
    super(DeckForm, self).__init__(*args, **kwargs)
    if hero:
        ...

请记住按关键字传递英雄参数:

return render(request, 'hsguides/guide_create.html', {
    'DeckForm': DeckForm(hero=hero),
    'GuideForm': GuideForm,
})