Question

Here is a simple model, with a field being unique:

class UserProfile(models.Model):
    nickname = models.CharField(max_length=20, unique=True)
    surname = models.CharField(max_length=20)

A view allows users to modify their profile using a ModelForm:

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile

def my_profile(request):
    ...
    if request.method == 'GET':
        # Below, 'profile' is the profile of the current user
        profile_form = UserProfileForm(instance=profile)
    else:
        profile_form = UserProfileForm(request.POST)
        if profile_form.is_valid():
            ... # save the updated profile

    return render(request, 'my_profile.html', {'form': form})

The problem is that is_valid() always returns False if the user does not change its nickname, because of the uniqueness check. I need the uniqueness check because I do not want one user to set its nickname to anothers, but it should not prevent a user from setting its nickname to its current nickname.

Do I have to rewrite the validation of the form, or did I miss something easier?

Was it helpful?

Solution

You have to pass the instance to both the unbound and the bound form:

else:
    profile_form = UserProfileForm(request.POST, instance=profile)
    if profile_form.is_valid():
        ... # save the updated profile

This will ensure that the current user's profile is updated, rather than a new profile being created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top