Foreign key request restriction for embedded form set in Django

I have a program (using Django 1.9) to track tournaments. Each tournament consists of a series of battles, and each battle has two people (combatants) associated with it.

The tournament has a "battle-beat" that contains a subset of all battle objects. The interface currently allows me to add / remove combatants from "battleant_pool".

The problem is with the screen, which allows me to record fights. I can view / add / delete / change battles without problems, but the problem with incoming messages is that the drop-down lists that allow me to choose "combatant_1" and "combatant_2" allow me to choose from ANY combatant in the database and what I only intended for combatants in "battleant_pool".

I looked through many other forums related to this problem, but no one seems to help me solve this problem.

class combatant(models.Model):
    first_name = models.CharField(max_length=100)

class tournament(models.Model):
    combatant_pool = models.ManyToManyField(combatant, blank=True)

class bout(models.Model):
    parent_tournament = models.ForeignKey(tournament, on_delete=models.CASCADE)
    combatant_1 = models.ForeignKey(combatant, on_delete=models.CASCADE, related_name='combatant1')
    combatant_2 = models.ForeignKey(combatant, on_delete=models.CASCADE, related_name='combatant2')
    outcome = models.CharField(max_length=10)   


def BoutsView(request, pk):
    ThisTournament = tournament.objects.get(id=pk)

    BoutInlineFormSet = inlineformset_factory(tournament, bout, fields=('combatant_1', 'outcome', 'combatant_2'), formset=BaseInlineFormSet)

    if request.method == "POST":
        formset = BoutInlineFormSet(request.POST, request.FILES, instance=ThisTournament)
        if formset.is_valid():
            formset.save()
            # Do something.
            return HttpResponseRedirect('/TournamentTracker/' + str(pk) + '/bouts')
    else:
        formset = BoutInlineFormSet(instance=ThisTournament)

    return render(request, 'tournament_bouts_update_form.html', {'formset': formset, 'pk': pk})
+4
source share
1 answer

And finally, I found a solution that works.

I just had to add this method to the view:

    def get_field_qs(field, **kwargs):
        if field.name in ['combatant_1', 'combatant_2']:
            return forms.ModelChoiceField(queryset=Tournament.objects.get(id=pk).combatant_pool)
        return field.formfield(**kwargs)

formfield_callback=get_field_qs

inlineformset_factory.

+3

Source: https://habr.com/ru/post/1622675/


All Articles