简体   繁体   中英

Django IntegrityError of this overriding save method

My Model

class Worksite(models.Model):
    firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE)
    name = models.CharField(max_length=50, unique=True, verbose_name="Şantiye Adı")

My save method

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = self.get_unique_slug()
        os.mkdir(BASE_DIR+'/file/'+slugify(str(self.firm).replace('ı','i'))+'/'+self.slug)
    return super(Worksite, self).save(self, *args, **kwargs)

My UpdateView

class WorksiteUpdateView(generic.edit.UpdateView):
    template_name = 'firm/worksite_update.html'
    model = Worksite
    form_class = WorksiteForm

    def get_success_url(self, *args, **kwargs):
        return reverse('firm:worksite_list')

IntegrityError : (1062, "Duplicate entry '1' for key 'PRIMARY'")

If the save method is deleted, the update process is successful. but this time the folder can not be created. so save method is necessary. but this error is annoying. where is the mistakes? Help pls.

Could it be that you are calling parent's method incorrectly? Try return super(Worksite, self).save(*args, **kwargs) (by removing extra self argument).

It's because you pass self argument when calling superclass method - super().save() . It should work fine, if you delete it:

return super(Worksite, self).save( *args, **kwargs)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM