0

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
1
  • remove s from poke_types, since the right field is named poke_type Commented Jul 29, 2020 at 15:43

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch. I'll use the count method going forward, too
1

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.')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.