How do you display foreign key names, not primary keys dynamically in Django forums as new records are added?
I have 3 child tables that all relate to a parent table via foreign key relationships. I created a form to add records to this parent table that also has these foreign key relationships. The form queries these children and show the querySet object with N records in each object. Thus, I took this approach to populating the fields as multi-choice:
# Form
class CreateMatch(forms.ModelForm):
p_choices = [(player.id, player.gamer_tag) for player in Players.objects.all()]
e_choices = [(event.id, event.name) for event in Events.objects.all()]
g_choices = [(game.id, game.name) for game in Games.objects.all()]
player_one = forms.ChoiceField(choices=p_choices)
player_two = forms.ChoiceField(choices=p_choices)
game = forms.ChoiceField(choices=g_choices)
event = forms.ChoiceField(choices=e_choices)
class Meta:
model = Matches
fields = ['player_one', 'player_two', 'player_one_score', 'player_two_score',
'game', 'event', 'round', 'losers']
This will ensure fields like player_one populates all human readable names in the form field as a dropdown.
# View
from .forms import CreateMatch
def add_match(request):
context = {
"title": "Add New Event"
}
if request.method == 'POST':
form = CreateMatch(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('add match') # Replace 'forum_home' with your actual URL name
else:
form = CreateMatch()
return render(request, 'add_match.html', {'form': form, 'context': context})
# Parent model
class Matches(models.Model):
player_one = models.ForeignKey(Players, on_delete=models.CASCADE,
related_name='%(class)s_player_one')
player_two = models.ForeignKey(Players, on_delete=models.CASCADE,
related_name='%(class)s_player_two')
player_one_score = models.IntegerField(default=0)
player_two_score = models.IntegerField(default=0)
game = models.ForeignKey(Games, on_delete=models.CASCADE, default=1)
event = models.ForeignKey(Events, on_delete=models.CASCADE)
round = models.CharField(max_length=100)
losers = models.BooleanField(default=False)
Pre-querying to show names, but not dynamics when new records added
Stock usage that shows objects, but is dynamic when new records added
The problem I am facing is when I add a new player or event or game to the database via a form, the fields for model above is stale until I restart the server. The CreateMatch object is created and rendered on startup. It doesn't refresh the querySets that populate the fields as new records are added. How can I make this dynamic and requery the data as new records are added without restarting the app WHILE also showing the human names, not objects or primary keys of the foreign key?