Answer the question
In order to leave comments, you need to log in
How to test models where in the overridden .save() save is used 2 times?
I have a category model, to identify it in the telegram bot, I use the pk_for_telegram field, where the line containing the category id is written. Accordingly, id appears only after saving the instance, my solution is this:
class Category(models.Model):
'''Модель категорий'''
name = models.CharField(max_length=255, help_text='Имя категории')
photo = models.ImageField(upload_to='category_img/', help_text='Фото категории')
slug = models.SlugField(max_length=100, unique=True)
pk_for_telegram = models.CharField(max_length=255, unique=True, blank=True, null=True, help_text='Используется в боте для поиска категории') # Нужен для идентификации в телеграм боте
max_count_product = models.IntegerField()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
self.pk_for_telegram = f'c||{self.pk}'
super(Category, self).save(*args, **kwargs)
def __str__(self):
return self.name
django.db.utils.IntegrityError: UNIQUE constraint failed: main_app_category.id
class ListProductViewTest(TestCase):
def setUp(self) -> None:
self.seller_user = User.objects.create(username='seller1', password='password')
self.super_user = User.objects.create(username='admin1', password='password', is_staff=True)
image = SimpleUploadedFile('image.jpg', content=b'', content_type='image/jpg')
self.category = Category.objects.create(name='category', photo=image, max_count_product=10)
self.subcategory = SubCategory.objects.create(name='subcategory', photo=image, category=self.category)
self.product = Product.objects.create(title='product', photo=image, price=Decimal('100.00'), count=10, weight=100, description='descrpit', subcategory=self.subcategory, )
def test_seller_requared(self):
factory = RequestFactory()
request = factory.get('')
request.user = self.seller_user
response = IndexView.as_view()(request)
self.assertEqual(response.status_code, 302)
def test_admin_requared(self):
factory = RequestFactory()
request = factory.get('')
request.user = self.super_user
response = IndexView.as_view()(request)
self.assertEqual(response.status_code, 200)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question