To apply 'update_session_auth_hash' in UpdateView

error occured at the code below.

class UserUpdate(LoginRequiredMixin, UpdateView):
model = User
form_class = ProfileUpdateForm
template_name = 'single_pages/profile_update.html'
success_url = reverse_lazy('single_pages:landing')
login_url = '/login/'
def form_valid(self, form):
    u = form.save()
    if u is not None:
        update_session_auth_hash(self.request, u)
    return super(UserUpdate, self).form_valid(form)

with the error message

IntegrityError at /update/8/
UNIQUE constraint failed: single_pages_profile.phoneNumber
Request Method: POST
Request URL:    http://127.0.0.1:8000/update/8/
Django Version: 3.2.13
Exception Type: IntegrityError
Exception Value:    
UNIQUE constraint failed: single_pages_profile.phoneNumber
Exception Location: C:\github\project\venv\lib\site- 
packages\django\db\backends\sqlite3\base.py, line 423, in execute

Seems like it's related to the model Profile, which is OnetoOne with the user like this:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phoneNumberRegex = RegexValidator(regex = r'^01([0|1||6|7|8|9]-?([0-9]{3,4})-?([0-9]{4})$')
phoneNumber = models.CharField(max_length=11, unique=True, validators=[phoneNumberRegex])
username = models.CharField(max_length=30)
email = models.EmailField(max_length=50)
address = models.CharField(max_length=200)

Although I don't want Profile to be a ForeignKey of user, I tried that once but the same error occured.

Lastly, this is forms.py

class ProfileUpdateForm(UserCreationForm):
phoneNumber = forms.CharField(required=False)
address = forms.CharField(required=False)
username = forms.CharField()
email = forms.EmailField()
password1 = forms.CharField()
password2 = forms.CharField()

class Meta(UserCreationForm.Meta):
    fields = UserCreationForm.Meta.fields + ('email',)
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.fields['username'].disabled = True


def save(self):
    user = super().save()
    profile = Profile.objects.create(
        user=user, phoneNumber=self.cleaned_data['phoneNumber'], address=self.cleaned_data['address'])
    return user

By the error message, problem is here:

profile = Profile.objects.create(
        user=user, phoneNumber=self.cleaned_data['phoneNumber'], address=self.cleaned_data['address'])

Thank you for the answer in advance.

The issue is not with update_session_auth_hash, instead it is happening because you are saving the form twice.

def form_valid(self, form):
    u = form.save()  #<-- Saving once
    if u is not None:
        update_session_auth_hash(self.request, u)
    return super(UserUpdate, self).form_valid(form)  # <-- Saving twice

Instead, you can return to the success url based on the object later. Like this:

def form_valid(self, form):
    u = form.save()
    if u is not None:
        update_session_auth_hash(self.request, u)
    return HttpResponseRedirect(self.redirect_to(u))
Back to Top