I’ve created some custom admin validation that works like I want EXCEPT under one circumstance.
It’s designed to check to make sure that a list created in a many-to-many field has the correct number of items (‘players’) and that the ratio of men:women on the list is acceptable.
def clean(self):
super(GameRosterForm, self).clean()
players = self.cleaned_data.get('players', None)
RosterRulesOn = self.cleaned_data.get('RosterRulesOn', None)
women = players.filter(sex='F')
womenPct = int((women.count()/float(players.count()))*100)
if RosterRulesOn is True and players.count() < 8:
raise ValidationError('Rosters must have at least 8 players. You have only selected %s.' % (players.count()))
if RosterRulesOn is True and players.count() > 18:
raise ValidationError('Rosters cannot have more than 18 players. You have selected %s.' % (players.count()))
if RosterRulesOn is True and womenPct < 40:
raise ValidationError('Women must make up at least 40 percent of roster. They only constitute %s percent now.' % (womenPct))
return self.cleaned_data
As I say it works fine most of the time, but when the user has yet to add a player to the m2m it returns an error: ‘list’ object has no attribute ‘filter’ with a reference to the women=players.filter(sex=’F’) line.
I’ve tried some “if” and “try” conditionals to try to bypass the problem, but can’t find a solution that works.
How about this: