Skip to content
Advertisement

django – inlineformset_factory with more than one ForeignKey

I’m trying to do a formset with the following models (boost is the primary):

class boost(models.Model):
   creator = models.ForeignKey(userInfo)
   game  = models.ForeignKey(gameInfo)
   name  = models.CharField(max_length=200)
   desc  = models.CharField(max_length=500)
   rules = models.CharField(max_length=500)
   subscribe = models.IntegerField(default=0)

class userInfo(models.Model):
   pic_url= models.URLField(default=0, blank=True)
   auth   = models.ForeignKey(User, unique=True)
   birth  = models.DateTimeField(default=0, blank=True)
   country= models.IntegerField(default=0, blank=True)

class gameInfo(models.Model):
   psn_id = models.CharField(max_length=100)
   name   = models.CharField(max_length=200)
   publisher = models.CharField(max_length=200, default=0)
   developer = models.CharField(max_length=200, default=0)
   release_date = models.DateTimeField(blank=True, null=True)

I want to display a form to add a Boost item, trying to do in this way :

TrophyFormSet = inlineformset_factory(db.gameInfo, db.boost, extra=1)
formset = TrophyFormSet()

Here are my questions :

1 – When rendered, the combo box for “Creator” shows a list of “db.userInfo” (literally)! I want this to display db.userInfo.auth.username that is already in the database… how to do this?

2 – In this way, where is my “db.gameInfo” to choose?

thank you! =D

======

czarchaic answered my question very well! But now I need just a little question:

When I use the modelform to create a form for the boost_trophy model :

class boost_trophy(models.Model):
   boost  = models.ForeignKey(boost)
   trophy = models.ForeignKey(gameTrophyInfo)
   # 0 - Obtiveis
   # 1 - Requisitos minimos
   type   = models.IntegerField(default=0)

class gameTrophyInfo(models.Model):
   game = models.ForeignKey(gameInfo)
   name = models.CharField(max_length=500)
   desc = models.CharField(max_length=500)
   type = models.CharField(max_length=20)

It works nice, but I want the form to show in the “game” box only a really small set of items, only the: gameTrophyInfo(game__name=”Game_A”) results. How can I do this?

Advertisement

Answer

If I understand you correctly:

To change what is displayed set the model’s __unicode__ function

class userInfo(models.Model):
  #model fields

  def __unicode__(self):
    return self.auth.username
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement