Question

My problem is similar to Django Passing Custom Form Parameters to Formset

Ive have these classes

class Game(models.Model):
    home_team = models.ForeignKey(Team, related_name='home_team')
    away_team = models.ForeignKey(Team, related_name='away_team')
    round = models.ForeignKey(Round)

TEAM_CHOICES = ((1, '1'), (2, 'X'), (3, '2'),)

class Odds(models.Model):
    game = models.ForeignKey(Game, unique=False)
    team = models.IntegerField(choices = TEAM_CHOICES)
    odds = models.FloatField()
    class Meta:
        verbose_name_plural = "Odds"
        unique_together = (
            ("game", "team"),
        )

class Vote(models.Model):
    user = models.ForeignKey(User, unique=False)
    game = models.ForeignKey(Game)
    score = models.ForeignKey(Odds)
    class Meta:
        unique_together = (
            ("game", "user"),)

And I've defined my own modelformset_factory:

def mymodelformset_factory(ins):
    class VoteForm(forms.ModelForm):
        score = forms.ModelChoiceField(queryset=Odds.objects.filter(game=ins), widget=forms.RadioSelect(), empty_label=None)
        def __init__(self, *args, **kwargs):
            super(VoteForm, self).__init__(*args, **kwargs)
        class Meta:
            model = Vote
            exclude = ['user']
    return VoteForm 

And I use it like this:

        VoteFormSet = modelformset_factory(Vote, form=mymodelformset_factory(v), extra=0)
        formset = VoteFormSet(request.POST, queryset=Vote.objects.filter(game__round=round, user=user))

This displays the form:

drop down box of Game(s) in the Round specified and is supposed to display 3 radio buttons for the Odds but I don't know what to pass as a parameter to the mymodelformset_factory.. If v = Game.objects.get(pk=1) it obviously only displays Game with pk=1 for ALL Games, What I need is v = Game.objects.get(pk="game who is connected to the odds regarding") if you catch my drift..

Was it helpful?

Solution

I think you want to make some changes to your custom factory function. It should return the formset class, not the form. How about this:

def make_vote_formset(game_obj, extra=0):
    class _VoteForm(forms.ModelForm):
        score = forms.ModelChoiceField(
            queryset=Odds.objects.filter(game=game_obj), 
            widget=forms.RadioSelect(), 
            empty_label=None)

        class Meta:
            model = Vote
            exclude = ['user',]
    return modelformset_factory(Vote, form=_VoteForm, extra=extra)

Then in your view code:

current_game = Game.objects.filter(id=current_game_id)
VoteFormSet = make_vote_formset(current_game)
formset = VoteFormSet(
             request.POST, 
             queryset=Vote.objects.filter(game__round=round, user=user))

OTHER TIPS

Another solution is to subclass BaseModelFormSet and override _construct_forms method. By default BaseFormSet _construct_form method is calling in _construct_forms with one argument only, i:

# django/forms/formsets.py
def _construct_forms(self):
    # instantiate all the forms and put them in self.forms
    self.forms = []
    for i in xrange(self.total_form_count()):
        self.forms.append(self._construct_form(i))

but there can be any number of keyword args:

# django/forms/formsets.py
def _construct_form(self, i, **kwargs):

So, here is my view method and form that receives additional parameter in init from _construct_form:

# view

def edit(request, id):
    class ActionsFormSet(BaseModelFormSet):
        department = request.user.userdata.department.pk

        def _construct_forms(self):
            self.forms = []
            for i in range(self.total_form_count()):
                self.forms.append(self._construct_form(i, dep=self.department))

    actions_formset = modelformset_factory(Action, form=ActionForm, extra=0, can_delete=True, formset=ActionsFormSet)
    ...


# form

class ActionForm(forms.ModelForm):
    def __init__(self, dep=0, *args, **kwargs):
        super(ActionForm, self).__init__(*args, **kwargs)
        self.fields['user'].choices = [(u.pk, u.first_name) for u in User.objects.filter(userdata__department=dep)]

    class Meta:
        model = Action
        exclude = ('req',)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top