class Restaurant(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=120, unique=True, verbose_name="Name")
direction = models.CharField(max_length=120, verbose_name="Direction")
phone = models.IntegerField()
slug = models.SlugField(blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return f'/res/{self.slug}'
@property
def full_name(self):
return self.name
def clean(self):
from django.core.exceptions import ValidationError
if len(str(self.phone))<=5:
raise ValidationError({'phone':('Enter Correct number.')})
clean() method is not working. My view.py code is as follow :
class RestaurantView(generics.ListCreateAPIView):
queryset=Restaurant.objects.all()
serializer_class=RestaurantSerializer
def get(self,request):
query=self.get_queryset()
serializer=RestaurantSerializer(query,many=True)
return Response(serializer.data)
def post(self,request):
serializer = RestaurantSerializer(data=request.POST)
if serializer.is_valid(raise_exception=True):
name=serializer.validated_data.get('name')
direction=serializer.validated_data.get('direction')
phone=serializer.validated_data.get('phone')
r=Restaurant()
r.name=name,
r.direction=direction,
r.phone=phone
r.save()
response={'msg':'Data Saved Successfully'}
return Response(response)
How can I handle the clean() method validation? I'm also validating data in serializer.py file but still i want to validate data in models clean() method.Thankx in advance.
Validation of django objects (docs):
There are three steps involved in validating a model:
- Validate the model fields -
Model.clean_fields()- Validate the model as a whole -
Model.clean()- Validate the field uniqueness -
Model.validate_unique()All three steps are performed when you call a model’s
full_clean()method.
So your method clean() is correct, you just need to call it before saving your model instance (it is not automatically called).
This can be done be just calling r.clean(), or you can do a full validation (the 3 steps mentioned above) by calling r.full_clean().
So in your code add the validation call before r.save():
...
r = Restaurant()
...
r.full_clean()
r.save()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With