title: Django : Error: 'duplicate key value violates unique constraint'
body: <p>I have to save images with s3 when creating a new object for my website.</p>
  <p>I have a code to save my images that I use in my model's save method.</p>
  <p>When I use the django administration panel, I can easily create my object without any error.</p>
  <p>It also works well when I send my data without adding an image.</p>
  <p>But when I try to create my object throught my view, I get this error : <code>Error: 'duplicate key value violates unique constraint « store_shop_pkey »' DETAIL: key (id)=(37) already exists</code></p>
  <p>I think that in my serializer's create method, I try to save my object twice : once for the image and once for the rest of my object's keys.</p>
  <p>I don't know how to resolve this issue.</p>
  <p>It works well with PUT method.</p>
  <p>Here is my code :</p>
  <p><strong>models.py :</strong></p>
  <pre><code>class Shop(models.Model):
  
      name = models.CharField(max_length=255)
      category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True)
      description = models.TextField(blank=True, null=True)
      path = models.CharField(max_length=255, unique=True, null=True, blank=True) # Set a null and blank = True for serializer
      mustBeLogged = models.BooleanField(default=False)
      deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7)
      message = models.TextField(null=True, blank=True)
      banner = models.ImageField(null=True, blank=True)
  
      def save(self, *args, **kwargs):
          try:
              &quot;&quot;&quot;If we want to update&quot;&quot;&quot;
              this = Shop.objects.get(id=self.id)
              if self.banner:
                  image_resize(self.banner, 300, 300)
                  if this.banner != self.banner:
                      this.banner.delete(save=False)
              else:
                  this.banner.delete(save=False)
          except:
              &quot;&quot;&quot;If we want to create a shop&quot;&quot;&quot;
              if self.banner:
                  image_resize(self.banner, 300, 300)
          super().save(*args, **kwargs)
  
      def delete(self):
          self.banner.delete(save=False)
          super().delete()
          
      def __str__(self):
          return self.name
  </code></pre>
  <p><strong>utils.py :</strong></p>
  <pre><code>def image_resize(image, width, height):
      # Open the image using Pillow
      img = Image.open(image)
      # check if either the width or height is greater than the max
      if img.width &gt; width or img.height &gt; height:
          output_size = (width, height)
          # Create a new resized “thumbnail” version of the image with Pillow
          img.thumbnail(output_size)
          # Find the file name of the image
          img_filename = Path(image.file.name).name
          # Spilt the filename on “.” to get the file extension only
          img_suffix = Path(image.file.name).name.split(&quot;.&quot;)[-1]
          # Use the file extension to determine the file type from the image_types dictionary
          img_format = image_types[img_suffix]
          # Save the resized image into the buffer, noting the correct file type
          buffer = BytesIO()
          img.save(buffer, format=img_format)
          # Wrap the buffer in File object
          file_object = File(buffer)
          # Save the new resized file as usual, which will save to S3 using django-storages
          image.save(img_filename, file_object)
  </code></pre>
  <p><strong>views.py :</strong></p>
  <pre><code>class ShopList(ShopListView):
      &quot;&quot;&quot;Create shop&quot;&quot;&quot;
      def post(self, request):
          &quot;&quot;&quot;For admin to create shop&quot;&quot;&quot;
          serializer = MakeShopSerializer(data=request.data)
          if serializer.is_valid():
              serializer.save()
              return Response(serializer.data)
          return Response(serializer.errors)
  </code></pre>
  <p><strong>serializers.py :</strong></p>
  <pre><code>class MakeShopSerializer(serializers.ModelSerializer):
      class Meta:
          model = Shop
          fields = '__all__'
  
      def create(self, validated_data):
          # validated_data.pop('path')
          path = validated_data[&quot;name&quot;].replace(&quot; &quot;, &quot;-&quot;).lower()
          path = unidecode.unidecode(path)
          unique = False
          while unique == False:
              if len(Shop.objects.filter(path=path)) == 0:
                  unique = True
              else:
                  # Generate a random string
                  char = &quot;abcdefghijklmnopqrstuvwxyz&quot;
                  path += &quot;-{}&quot;.format(&quot;&quot;.join(random.sample(char, 5)))
          shop = Shop.objects.create(**validated_data, path=path)
          shop.save()
          return shop
      
      def update(self, instance, validated_data):
          #You will have path in validated_data
          #And you may have to check if the values are null
          return super(MakeShopSerializer, self).update(instance, validated_data)
  </code></pre>
  <p>Finally, this is the data that I send :</p>
  <p><a href="https://i.stack.imgur.com/LJTSw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LJTSw.png" alt="Data send" /></a></p>
  <p>Thank you by advance for your help</p>