Check ModelForm Model with Unique Field = True

Here is a simple model with a unique field:

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

The view allows users to modify their profile using 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 it is_valid()always returns Falseif the user does not change his nickname, because of the uniqueness check. I need a uniqueness check because I do not want one user to set his nickname to another, but he should not prevent the user from setting his nickname in his current nickname.

Should I rewrite form validation or am I missing something simpler?

+4
source share
1 answer

, :

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

, .

+2

Source: https://habr.com/ru/post/1540289/


All Articles