S
S
SHEZAR2018-10-23 16:17:29
Django
SHEZAR, 2018-10-23 16:17:29

How to fix this error:IntegrityError at /accounts/register/ UNIQUE constraint failed: accounts_userprofile.user_id?

#views.py
from django.shortcuts import render, redirect
from accounts.forms import RegistrationForm, EditProfileForm, UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required


def register(request):
    registered = False

    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        profile_form = UserProfile(request.POST)
        if user_form.is_valid() and profile_form.is_valid():

            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()

            registered = True
        return redirect('accounts/')

    else:
        user_form = RegistrationForm()

        profile_form = UserProfile()

    args = {'user_form': user_form, 'profile_form': profile_form}

    return render(request, 'registration/reg_form.html', args)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Guest007, 2018-10-24
@Guest007

You are trying to create a second Profile for a user, and there is most likely OneToOneField (or ForeignKey with unique=True).
Do a check: If there is a profile, then we take it and update it. If not, we create. Although it is better to create a profile at the same time as creating an Account and then always only update the record without trying to create.
And so - yes, without a trace, code and a list of used packages, you can only speak general words ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question