Reputation: 79
I'm trying to put together a simple little app that allows users to keep track of their own pokemon. Each pokemon has 1-2 different 'types' (e.g. fire, water, etc.), so I've added in a clean
function to limit the maximum number of types the user can select. However, when trying to add a pokemon I am given the following error:
AttributeError at /admin/pokollector/custompokemon/add/
'CustomPokemon' object has no attribute 'poke_types'
I'm assuming this has something to do with the poke_types
variable not being properly inherited, but I have no idea why that would be.
Here is the code from my models.py
file:
from django.db import models
from django.core.validators import MinValueValidator as min, MaxValueValidator as max
from django.core.exceptions import ValidationError
class PokeType(models.Model):
poke_type = models.CharField(max_length=15)
def __str__(self):
return self.poke_type
#Current generation of games for gen_added field
gen = 8
class Pokemon(models.Model):
poke_name = models.CharField(max_length=30)
poke_type = models.ManyToManyField(PokeType)
evolves_from = False
evolves_into = False
gen_added = models.PositiveIntegerField(validators=[min(1), max(gen)])
def clean(self):
#Allow max of 2 poke_types to be selected
if len(self.poke_types > 2):
raise ValidationError('A Pokemon has a maximum of two types.')
class Meta:
verbose_name_plural = 'Pokemon'
abstract = True
class CustomPokemon(Pokemon):
name = models.CharField(max_length=30)
level = models.PositiveIntegerField(blank=True, null=True)
def __str__(self):
return self.name
Upvotes: 0
Views: 149
Reputation: 1856
Just had a few typos with the attribute name and having the comparison inside the len() call.
def clean(self):
#Allow max of 2 poke_types to be selected
if len(self.poke_type) > 2:
raise ValidationError('A Pokemon has a maximum of two types.')
Upvotes: 1
Reputation: 1382
I think there is problem in your clean function. Try.
def clean(self):
#Allow max of 2 poke_types to be selected
if self.poke_type.count() > 2:
raise ValidationError('A Pokemon has a maximum of two types.')
It seems you mistyped.
Plus, don't use len
function. When you use len
, the count happens on python which is slow. Use count
function so that the count occurs in database level.
Upvotes: 2