Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formfield_for_foreignkey and Inline Admin

I only want to show the players related to team in a particular fixture. Normally when I do it, it shows me all my players from the database. Here is my models.py

class InningsCard(models.Model):
    fixture = models.ForeignKey(Fixture)
    team = models.ForeignKey(Team)
    runs = models.IntegerField(max_length=6, default=0)
    wickets = models.IntegerField(max_length=6, default=0)
    overs = models.FloatField(max_length=6, default=0.0)

    def __unicode__(self):
        return str(self.team)

class BattingDetail(models.Model):
    STATUS_CHOICES = (
        ('no', 'not out'),
        ('bowled', 'bowled'),
        ('caught', 'caught'),
        ('lbw', 'lbw'),
    )
    innings = models.ForeignKey(InningsCard)
    player = models.ForeignKey(Player)
    runs = models.IntegerField(max_length=5, default=0)
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='no')

    def __unicode__(self):
        return str(self.player)

Now and here is my admin.py to include formfield_for_foreignkey, but it doesn't work.

class BattingInline(admin.TabularInline):
    model = BattingDetail
    extra = 0

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

        if db_field.name == 'player':
            kwargs = Player.objects.filter(team = request.team)
        else:
            pass

        return super(BattingInline, self).formfield_for_foreignkey(db_field, request, **kwargs)


class InningCardAdmin(admin.ModelAdmin):
    inlines = [BattingInline]

where could i be going wrong?

//mouse

like image 283
Yousuf Jawwad Avatar asked Mar 09 '12 19:03

Yousuf Jawwad


1 Answers

  1. You're replacing the entire kwargs with the queryset. kwargs must be a dictionary, and the particular key you're looking for is 'queryset':

    kwargs['queryset'] = Player.objects.filter(team=request.team)
    
  2. I'm almost positive request isn't going to actually have an attribute team. Unless you've added it yourself in some code not displayed here, you need to find another way to get at the current "team". You can parse out the team id from request.path and use that for the lookup, for example.

As a side note, the else clause is unnecessary if you're just going to pass there.

like image 110
Chris Pratt Avatar answered Oct 17 '22 12:10

Chris Pratt