Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix UNIQUE constraint failed: users_profile.user_id?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading