I have a form in a template where I want the ability to check a box and it shows an interest in a game for an official. There is a many-to-many relationship between games and officials.
In the template, the form presents only the user of all officials to either check or uncheck for a game.
If the user makes any change (checks or unchecks), they essentially uncheck all users associated with that game.
Please help point me in the right direction.
Here are relevant sections of code:
models.py
class Official(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Game(models.Model):
game_official_options = models.ManyToManyField(Official, blank=True, related_name='officials')
view.py
def GameDetail(request, slug):
game = officials_models.Game.objects.get(slug=slug)
if request.method == "POST":
form = officials_forms.GameInterestForm(request.user, request.POST, instance=game)
if form.is_valid():
post = form.save(commit=False)
post.save()
form.save_m2m()
return HttpResponseRedirect(request.path_info)
else:
form = officials_forms.GameInterestForm(instance=game, user=request.user)
context = {'form': form, 'game': game}
return render(request, 'officials/game.html', context)
forms.py
class GameInterestForm(forms.ModelForm):
class Meta:
model = Game
fields = ('game_official_options',)
labels = {'game_official_options': 'Check the box next to your name if you are interested in participating in this game'}
def __init__(self, user, *args, **kwargs):
super(GameInterestForm, self).__init__(*args, **kwargs)
self.fields["game_official_options"].widget = CheckboxSelectMultiple()
self.fields["game_official_options"].queryset = Official.objects.filter(user=user)
From the html template
{% if user.official %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Change your interest status" onclick="return confirm('Your choice is saved.')">
</form>
{% endif %}
I think the issue is that I am filtering a queryset in the forms.py that only presents the one user (what I want to see), but when it saves, it is saving for all users as if queryset was objects.all() instead of objects.filter(user=user)
Should I filter by user and pass that to the form first somehow?