[Answer]-UserProfile id == None in form validation / save

1👍

profile.id field is set in the profile.save() method then profile created first time.

IntegrityError is raised because you trying to create new UserProfile instead of saving old one. To solve this problem you should pass the instance parameter to ProfileForm constructor:

form = ProfileForm(request.POST,
                   instance=UserProfile.objects.get(user=request.user))

EDIT: If you want edit and create profile in single view then read profile to edit using first() instead of get():

def edit_profile(request):
    profile = UserProfile.objects.filter(user=request.user).first()
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            ...
    else:
        form = ProfileForm(instance=profile)

Leave a comment