dimanche 1 mars 2015

Error in Django Test using Factory Boy

I use Factory Boy in my Django project. Could you please explain my mistake to me: why am I having the error when I ran 'tests.py' - 'ValueError: "" needs to have a value for field "post" before this many-to-many relationship can be used.'


Here is my code:



# factories


class TagFactory(factory.Factory):
class Meta:
model = models.Tag

name = factory.Sequence(lambda n: 'tag-%s' % n)
slug = factory.Sequence(lambda n: 'slug-%s' % n)


class CategoryFactory(factory.Factory):
class Meta:
model = models.Category

name = factory.Sequence(lambda n: 'cat-%s' % n)
slug = factory.Sequence(lambda n: 'cat-slug-%s' % n)


class PostFactory(factory.Factory):
class Meta:
model = models.Post

title = factory.Sequence(lambda n: 'postik-%s' % n)
text = 'some text'
slug = factory.Sequence(lambda n: 'post_slug_%s' % n)
category = factory.SubFactory(CategoryFactory)

@factory.post_generation
def tags(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
for tag in extracted:
self.tags.add(tag)


tests.py



class PostTests(TestCase):
"""
display_post view test.
"""
def setUp(self):
self.tag = factories.TagFactory()
self.category = factories.CategoryFactory()
self.poster = factories.PostFactory.create(tags=('tag-1'))

...


models.py



class Category(models.Model):
"""
Category.
"""

name = models.CharField(max_length=20)
slug = models.SlugField(max_length=20)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('categorier', args=[str(self.slug)])


class Tag(models.Model):
"""
Tag.
"""

name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('tagger', args=[str(self.slug)])

class Meta:
verbose_name = _('Tag')


class Post(models.Model):
"""
Post model.
"""

title = models.CharField(max_length=150)
created_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="pictures/%Y/%m/%d",
blank=True, null=True)
text = RichTextField(max_length=10000)
slug = models.SlugField(max_length=150, unique=True)
tags = models.ManyToManyField(Tag, null=True, blank=True)
category = models.ForeignKey(Category)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('poster', args=[str(self.slug)])

class Meta:
ordering = ['-created_date']
verbose_name = _('Eco Post')
verbose_name_plural = _('Eco Posts')

Aucun commentaire:

Enregistrer un commentaire