Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model validate_unique method don't raise ValidationError

My model is :

class Inventory(models.Model):
    canteen_id = models.IntegerField()
    item = models.OneToOneField('Info',db_column='item_id')

I want item should be unique for each canteen_id. I used unique_togetherbut its not working as item is in OneToOneField. I am using validate_unique method for my model and my code is now:

class Inventory(models.Model):
    canteen_id = models.IntegerField()
    item = models.OneToOneField('Info',db_column='item_id')
    unit_price = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    sales_vat = models.DecimalField(decimal_places=2,max_digits=5,default=0.0)
    date_time = models.DateField(auto_now=False,auto_now_add=True)

def vat_count(self):
    self.item_price = Decimal(self.unit_price)
    self.vat = (self.item_price * 15)/100
    return self.vat

def validate_unique(self, exclude=None):
    qs = Inventory.objects.filter(canteen_id=self.canteen_id)
    if self.pk is None:
        if qs.filter(item=self.item).exists():
            raise ValidationError("item already exists")


def save(self, *args,**kwargs):
    self.canteen_id = CANTEEN_ID
    self.sales_vat = self.vat_count()
    self.unit_price = Decimal(self.unit_price) 
    self.validate_unique()
    super(Inventory,self).save(*args, **kwargs) 

Now when I am trying to add same item and canteen_id, it don't raise any error message in form page. It shows error. Error:

Environment:   
Request Method: POST
Request URL: http://localhost:8000/admin/item/inventory/add/

Django Version: 1.9.2
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'item',
 'bill',
 'system']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
  541.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
  244.             return view(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
  1437.         return self.changeform_view(request, None, form_url, extra_context)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
  67.             return bound_func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
  63.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
  184.                     return func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view
  1378.                 self.save_model(request, new_object, form, not add)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model
  991.         obj.save()

File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in save
  34.         self.validate_unique()

File "/home/harun/Desktop/nutboltu/canteenLatest/CanteenKiosk/diucanteen/item/models.py" in validate_unique
  27.                 raise ValidationError("item already exists")

Exception Type: ValidationError at /admin/item/inventory/add/
Exception Value: [u'item already exists']

What is the solution???

like image 573
Harun-Ur-Rashid Avatar asked Feb 07 '23 12:02

Harun-Ur-Rashid


1 Answers

If you override validate_unique method in your model you should call super as you do in save/delete etc.

def validate_unique(self, exclude=None):
    # custom logic
    super(Inventory, self).validate_unique(exclude=exclude)
like image 83
alTus Avatar answered Feb 12 '23 15:02

alTus