Reputation: 139
I am using the inbuilt User model to store user information in my application. However while registering a new user I want that the username should be unique. For this purpose I decided to override the clean_username method in my modelform. Here is my forms.py file
from django import forms
from django.contrib.auth.models import User
class Registration_Form(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput())
class Meta:
model=User
fields=['first_name', 'last_name', 'username', 'email', 'password']
def clean_username(self):
value=self.cleaned_data['username']
if User.objects.filter(username=value[0]):
raise ValidationError(u'The username %s is already taken' %value)
return value
And here is my views.py file
from django.shortcuts import render
from django.shortcuts import redirect
# Create your views here.
from django.contrib.auth.models import User
from registration.forms import Registration_Form
def register(request):
if request.method=="POST":
form=Registration_Form(request.POST)
if form.is_valid():
unm=form.cleaned_data('username')
pss=form.cleaned_data('password')
fnm=form.cleaned_data('first_name')
lnm=form.cleaned_data('last_name')
eml=form.cleaned_data('email')
u=User.objects.create_user(username=unm, password=pss, email=eml, first_name=fnm, last_name=lnm)
u.save()
return render(request,'success_register.html',{'u':u})
else:
form=Registration_Form()
return render(request,'register_user.html',{'form':form})
However on clicking the submit button of the form I am getting this error
Exception Type: TypeError
Exception Value:
'dict' object is not callable
Exception Location: /home/srai/project_x/registration/views.py in register, line 12
The line in question is this
unm=form.cleaned_data('username')
Can anyone please tell me why this error occurs and how do I solve it. Thanks.
Upvotes: 0
Views: 178
Reputation: 600059
Firstly, the error isn't anything to do with your custom clean method, it is happening in the view.
It is simply that you should use square brackets to access dict items, not parentheses:
unm=form.cleaned_data['username']
Upvotes: 1