Home > Net >  How to fix UNIQUE constraint failed: users_profile.user_id?
How to fix UNIQUE constraint failed: users_profile.user_id?

Time:12-29

How to fix UNIQUE constraint failed: users_profile.user_id? already have a created profile

views.py

class EditProfile(CreateView):
    model = Profile
    context_object_name = 'profile'
    template_name = 'users/profile_edit.html'

    fields = ['avatar', 'name', 'description']
    success_url = reverse_lazy('users:profile')

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

urls.py

path('<slug:slug>/edit/', EditProfile.as_view(), name='profile_edit'),

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='users/avatars/%Y/%m/%d/', blank=True)
    name = models.CharField(max_length=20, blank=True)
    description = models.CharField(max_length=250, blank=True)
    slug = models.SlugField(max_length=50, blank=True)

    def __str__(self):
        return f"{self.user}"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Profile, self).save(*args, **kwargs)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

enter image description here

CodePudding user response:

You cannot use CreateView to Edit existing object. To Edit profile you should use UpdateView, because CreateView is trying to create NEW Profile object with request.user object, that already has got corresponding Profile object.

  • Related