Issue
class Person(models.Model):
SHIRT_SIZES = [
("S", "Small"),
("M", "Medium"),
("L", "Large"),
]
first_name = models.CharField("person's first name:", max_length = 30, help_text = "User First name")
last_name = models.CharField("Person's Last Name:",max_length = 30, help_text = "User Last name")
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES, default = "S", help_text = "User shirt size")
def __str__(self) -> str:
return self.first_name + ' ' + self.last_name
def full_name(self):
return '%s %s' %(self.first_name, self.last_name)
def get_absolute_url(self):
return "/people/%i/" % self.id;
def save(self, *args, **kwargs):
self.first_name = "%s %s" %('Mr', self.first_name)
return super().save(self, *args, **kwargs)
Creating a new record is working fine but it's generating an error when updating the existing record.
IntegrityError at /admin/members/person/14/change/ UNIQUE constraint failed: members_person.id Request Method: POST Request URL: http://127.0.0.1:8000/admin/members/person/14/change/ Django Version: 3.2.23 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: members_person.id Exception Location: C:\wamp\www\python\myproject\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\wamp\www\python\myproject\Scripts\python.exe Python Version: 3.6.6 Python Path: ['C:\\wamp\\www\\python\\vleproject', 'C:\\wamp\\www\\python\\myproject\\Scripts\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'C:\\wamp\\www\\python\\myproject', 'C:\\wamp\\www\\python\\myproject\\lib\\site-packages'] Server time: Fri, 12 Jan 2024 13:11:09 +0000
Solution
You should not include self
in the super()
call:
def save(self, *args, **kwargs):
self.first_name = "%s %s" %('Mr', self.first_name)
return super().save(*args, **kwargs)
But this is not a good idea anyway: it will each time add an extra Mr
in front.
Answered By - gladiator
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.