¿Cómo puedo tener un modelformset con modelform en línea?

Digamos que tengo un modelo como:

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)

Entonces, en mi opinión, tengo:

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 y 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?

preguntado el 24 de agosto de 12 a las 08:08

For me it is completely unclear, why you think you need an inline model formset (which is by the way with your models not possible anyway)? Why do you want to have char fields instead of the dropdowns? This does not seem to be logical to me, so I am afraid I miss some information or I misunderstand the provided information. -

@schacki Client wants to supply the team name in the same form as he edits or creates a game. It seems perfectly fine to me that he should be able to create/update the team on the same screen as the game. :) -

Understand, I personally would prefer an nice and easy drop down instead of typing, but that is a matter of taste. Just be aware that you will create a new team now for every type. And again: this is not an inline model formset :-). -

1 Respuestas

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:

from django import forms

from models import Team, Game    


class GameUpdateForm(forms.ModelForm):
    home_team_name = forms.CharField(max_length=20)
    away_team_name = forms.CharField(max_length=20)

    def save(self):
        obj = super(GameForm, self).save()

        if not obj.home_team_id:
            obj.home_team = Team()
        obj.home_team.name = self.cleaned_data.get('home_team_name')
        obj.home_team.save()

        if not obj.away_team_id:
            obj.away_team = Team()
        obj.away_team.name = self.cleaned_data.get('away_team_name')
        obj.away_team.save()

        return obj
    class Meta:
        model = Game
        exclude = ('home_team', 'away_team')

And make the modelformset use it:

GameFormSet = modelformset_factory(Game, form=GameForm, extra=1)

Es posible que también desee agregar CharField autocompletion.

Respondido 24 ago 12, 10:08

I like this and would accept it if my name field was unique, but I can't make them unique. :( - kit sunde

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.