0

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.

4

1 回答 1

1

首先,错误与您的自定义清理方法无关,它发生在视图中。

很简单,您应该使用方括号来访问 dict 项目,而不是括号:

unm=form.cleaned_data['username']
于 2015-03-25T23:33:56.367 回答