Say I have a model like:
class Team(models.Model):
name = models.CharField(max_length=20)
class Game(models.Model):
title = models.CharField(ma_length=20)
home_team = models.ForeignKey(Team)
away_team = models.ForeignKey(Team)
Then in my view I have:
def manage_games(request):
GameFormSet = modelformset_factory(Game, extra=1)
game_forms = GameFormSet(request.POST or None,
queryset=Game.objects.all())
if request.method == "POST":
if game_forms.is_valid():
game_forms.save()
game_forms = GameFormSet(queryset=Game.objects.all())
return render(request, "admin_dashboard/manage_games.html", locals())
This works okay except that I’d like to be able to turn the home_team and away_team into CharFields (rather than the dropdown it currently is) while also keeping them separate models. How can I add an inline model formset into a model formset to make this possible?
An inlinemodelformset wouldn’t work because Game has the foreignkeys Team.
An inlinemodelformset can show a list of forms for models which are connected to another via a ForeignKey. For example if A.b is an FK to B, then it is possible to make an inlinemodelformset of A for B.
However, you could still add a couple of fields to change the home/away team names:
And make the modelformset use it:
You might also want to add CharField autocompletion.