I am building a game tracker. I would like to have it where if the user selects anything other than ‘Win’ then the wincon field of the form is unchangeable or set to a default field. This is to make it easier to understand that when they don’t win they shouldn’t add a wincon. It would also be nice if the user had a blank field that if they didn’t want to input a wincon then it would default to ‘——‘
Ideally if it is a win then the wincon field would be able to be changed.
But if a loss is selected then the form defaults to null or a prepopulated field like ‘——‘
models.py
class Profile(models.Model):
user = models.ForeignKey(User,
max_length=10,
on_delete=models.CASCADE,
null=True)
def __str__(self):
return str(self.user)
class Wincon(models.Model):
wincon = models.CharField(max_length=100,)
user = models.ForeignKey(User,
max_length=10,
on_delete=models.CASCADE,
null=True)
def __str__(self):
return self.wincon
class Game(models.Model):
# ForeignKeys
user = models.ForeignKey(User,
max_length=10,
on_delete=models.CASCADE,
null=True)
wincon = models.ForeignKey(Wincon,
on_delete=models.CASCADE,
null=True,
blank=True,)
views.py
@login_required(login_url='my-login')
def wincon(request):
wincon_list = Wincon.objects.filter(user=request.user)
user = User.objects.get(username=request.user)
if request.method == "POST":
wincon_form = WinconForm(request.POST)
if wincon_form.is_valid():
obj = wincon_form.save(commit=False)
obj.user = request.user
obj.save()
return HttpResponseRedirect('/wincon')
else:
wincon_form = WinconForm()
context = {'wincon_form': wincon_form, 'wincon_list': wincon_list, 'user': user}
return render(request, 'gametracker_app/wincon.html', context=context)
forms.py
class GameForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
# Set wincon list shown to only wincon from user
user_wincon = Wincon.objects.filter(user=user)
user_wincon_list = []
for wincon in user_wincon:
user_wincon_list.append((wincon.id, wincon.wincon))
self.fields['wincon'].choices = user_wincon_list
class Meta:
model = Game
exclude = {'date', 'time', 'user'}
labels = {
'num_players': '# of Players',
'start_pos': 'Starting position',
'mull': 'Starting hand',
'outcome': 'Outcome',
'wincon': 'Your Wincon',
}
In my forms.py I tried to add a default wincon like below
class GameForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
# Set wincon list shown to only wincon from user
user_wincon = Wincon.objects.filter(user=user)
user_wincon_list = [(0, '------')]
for wincon in user_wincon:
user_wincon_list.append((wincon.id, wincon.wincon))
self.fields['wincon'].choices = user_wincon_list
But that just creates a default of ‘——‘ and if left selected then the form throws an error of
“Select a valid choice. That choice is not one of the avaiable choices.”