Django如何保存自定义formset

时间:2009-09-09 03:15:57

标签: django forms dynamic formset

我已经编写了以下自定义formset,但对于我的生活,我不知道如何保存表单。我搜索了Django文档并进行了大量搜索,但没有一个解决方案有效。很多兔子洞,但没有肉;-)有人能指出我正确的方向吗?

// views.py partial //

@login_required

def add_stats(request, group_slug, team_id, game_id, template_name = 'games/stats_add_form.html'):

    if request.POST:

        formset = AddStatsFormSet(group_slug=group_slug, team_id=team_id, game_id=game_id, data=request.POST)

        if formset.is_valid():

            formset.save()

            return HttpResponseRedirect(reverse('games_game_list'))

        else:

            formset = TeamStatFormSet(group_slug=group_slug, team_id=team_id, game_id=game_id)

        return render_to_response(template_name, {'formset': formset,})


// modles.py partial //

class PlayerStat(models.Model):

    game = models.ForeignKey(Game, verbose_name=_(u'sport event'),)
    player = models.ForeignKey(Player, verbose_name=_(u'player'),)
    stat = models.ForeignKey(Stat, verbose_name=_(u'statistic'),)
    total = models.CharField(_(u'total'), max_length=25, blank=True, null=True)

    class Meta:
        verbose_name = _('player stat')
        verbose_name_plural = _('player stats')
        db_table     = 'dfusion_playerstats'

        def __unicode__(self):
            return u'%s' % self.player


// forms.py

class TeamStatForm(forms.Form):

    total = forms.IntegerField()


class BaseTeamStatsFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        self.group_slug = kwargs['group_slug']
        self.team_id = kwargs['team_id']
        self.game_id = kwargs['game_id']
        self.extra = len(Stat.objects.filter(group__slug=self.group_slug))
        del kwargs['group_slug']
        del kwargs['game_id']
        del kwargs['team_id']
        super(BaseTeamStatsFormSet, self).__init__(*args, **kwargs)

    def add_fields(self, form, index):
        super(BaseTeamStatsFormSet, self).add_fields(form, index)
        form.fields["stat"] = forms.ModelChoiceField(queryset = Stat.objects.filter(group__slug=self.group_slug))
        form.fields["game"] = forms.ModelChoiceField(queryset = Game.objects.all())
        form.fields["team"] = forms.ModelChoiceField(queryset = Team.objects.all())
        form.fields["game"].initial = self.game_id
        form.fields["team"].initial = self.team_id

TeamStatFormSet = formset_factory(TeamStatForm, BaseTeamStatsFormSet)

2 个答案:

答案 0 :(得分:7)

在自定义表单中,您需要添加一个save()方法,根据需要将表单数据填充到模型中。表单中输入的所有数据都将在名为cleaning_data []的散列中提供。

例如:

def save(self):
    teamStat = TeamStat(game_id=self.cleaned_data['game_id'],team_id=self.cleaned_data['team_id'])
    teamStat.save()
    return teamStat

答案 1 :(得分:3)

只有模型表单和表单集附带save()方法。常规表单不附加到模型,因此您必须自己存储数据。来自Django邮件列表的How to save a formset?有一个从常规表单集中保存数据的示例。

编辑:您可以随时向常规表单或formset添加save()方法,如gbc建议的那样。他们只是没有内置的。

我在您的代码段中没有看到TeamStat模型,但如果您有一个,forms.py应该是这样的:

class TeamStatForm(forms.ModelForm):
    total = forms.IntegerField()

    class Meta:
        model = TeamStat


class BaseTeamStatsFormSet(BaseModelFormSet):

    def __init__(self, *args, **kwargs):
        self.group_slug = kwargs['group_slug']
        self.team_id = kwargs['team_id']
        self.game_id = kwargs['game_id']
        self.extra = len(Stat.objects.filter(group__slug=self.group_slug))
        del kwargs['group_slug']
        del kwargs['game_id']
        del kwargs['team_id']
        super(BaseTeamStatsFormSet, self).__init__(*args, **kwargs)

    def add_fields(self, form, index):
        super(BaseTeamStatsFormSet, self).add_fields(form, index)
        form.fields["stat"] = forms.ModelChoiceField(queryset = Stat.objects.filter(group__slug=self.group_slug))
        form.fields["game"] = forms.ModelChoiceField(queryset = Game.objects.all())
        form.fields["team"] = forms.ModelChoiceField(queryset = Team.objects.all())
        form.fields["game"].initial = self.game_id
        form.fields["team"].initial = self.team_id

TeamStatFormSet = modelformset_factory(TeamStatForm, BaseTeamStatsFormSet)

请参阅Django文档中的Creating forms from models