32👍
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.
8👍
You can write function to check the username if exists like this:
@ggorlen, thanks! Update:
from django.contrib.auth.models import User
def username_exists(username):
return User.objects.filter(username=username).exists()
from django.contrib.auth.models import User
def username_exists(username):
if User.objects.filter(username=username).exists():
return True
return False
- [Django]-Map object is not JSON serializable
- [Django]-Django testing model with ImageField
- [Django]-Get list item dynamically in django templates
0👍
This is how I managed to make it work (assuming you have a logged in user):
forms.py
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import User
class MyUserChangeForm(UserChangeForm):
def __init__(self, *args, **kwargs):
super(MyUserChangeForm, self).__init__(*args, **kwargs)
del self.fields['password']
class Meta:
model = User
fields = ('username', 'first_name')
views.py
def home(request):
if request.method == 'POST':
form = MyUserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = MyUserChangeForm(instance=request.user)
return render(request, 'change_user.html', {"form": form})
- [Django]-Feedback on using Google App Engine?
- [Django]-Change model class name in Django admin interface
- [Django]-How do I write Facebook apps using Django?