Originally I had this in my models.py
def validate_project_name(value,self):
project_name = Team.objects.filter(Project_name=value)
if self.pk:
project_name = project_name.exclude(pk=self.pk)
if project_name:
raise ValidationError('This already exists.')
class Team(models.Model):
Project_name = models.CharField(max_length=250, validators=[validate_project_name])
Project_number = models.IntegerField()
This worked in the sense that it will not allow users to input an already existing Project_name
. However, now I have incorporated an edit/update functionality. So if a user wants to update his/her own Team
, it will raise the ValidationError since it exists in the database. So for example, if the User wants to keep the same Project_name
but update the Project_number
the error will raise. So I want to exclude self
from the queryset. I looked at this example:
django exclude self from queryset for validation
So I simply added the following code within my class Team
.
def clean_name(self):
project_name = self.cleaned_data['Project_name'].title()
qs = Team.objects.filter(Project_name=project_name)
if self.instance.pk is not None:
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise ValidationError("This already exists")
But it is not working as in the validation error is not being raised...Any ideas?
Can you make sure clean_name
is even getting called? I was under the impression that models only had a clean
method, not a method for each individual field (that syntax is used for forms). Try using just def clean(self):
https://docs.djangoproject.com/en/1.10/ref/models/instances/#django.db.models.Model.clean
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.