I am working on a Django project where users will be able to change their usernames along with their first and last name in one form. In forms.py, I am trying to find out if the user exists. If so, it should display an error.
The problem is that if user wants to change his first and last name and leaves his username in the input, it raises a validation error. Obviously, that username already exists.
Is there a way to check if it equals the username of currently logged user and avoid displaying the error?
class ChangeNameForm(forms.ModelForm):
username = forms.CharField(max_length=30)
first_name = forms.CharField(max_length=255)
last_name = forms.CharField(max_length=255)
def clean_username(self):
username = self.cleaned_data['username']
try:
user = User.objects.get(username=username)
except user.DoesNotExist:
return username
raise forms.ValidationError(u'Username "%s" is already in use.' % username)
objects. filter(username=self. cleaned_data['username']). exists(): # Username exists ...
objects. filter(username=username). exists() if not user_exist: # create your user new_user = User(username=username) new_user. email = email new_user.
When ModelForms are bound to a model object, they have an attribute called 'instance', which is the model object itself. In your view, when request.method == 'POST'
, you're probably creating the form instance like this:
form = ChangeNameForm(request.POST, instance=request.user)
If that's the case, you can access the logged user from the form methods, and your validation method can be something like this:
def clean_username(self):
username = self.cleaned_data['username']
try:
user = User.objects.exclude(pk=self.instance.pk).get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(u'Username "%s" is already in use.' % username)
Consider using the .exists method, for it issues a faster query to your database than if you try to retrieve all the user information with the .get method. And the code gets a little cleaner too:
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists():
raise forms.ValidationError(u'Username "%s" is already in use.' % username)
return username
Optionally, you can also follow these guidelines when raising the ValidationError.
I can't test this code right now, so I apologize if there's anything wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With