问题
I've been stuck on this for a while now and can't seem to figure out what's going on. I'm just starting to learn Django and I got my login set up and now want to implement a registration page.
I used the UserCreationForm form at first and that worked fine, but I want to add fields for Email, First name, and Last name. I figured I could just subclass UserCreationForm and add the fields but that doesn't seem to work. Also I tried overriding the save method, but it still doesn't work.
My custom form looks like this:
class RegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=75)
class Meta:
model = User
fields = ("first_name", "last_name", "email",)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
The view to handle this is the following:
def Register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user = form.save();
new_user = authenticate(username=request.POST['username'], password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect('/members/home')
else:
form = RegistrationForm()
return render_to_response('register.html', {'form' : form}, context_instance=RequestContext(request))
The form loads just fine with the new fields and everything, but when I submit I get the error:
AttributeError at /register/
'AnonymousUser' object has no attribute 'backend'
Oh, and also I'm using Django 1.3.
Any idea what I'm doing wrong?
回答1:
My guess is that your meta class fields
doesn't include username
.
You are inheriting the form field from UserCreationForm
but it's not saving to the User
model and therefore authenticate
is failing, and crashing on login()
The docs suggest you check whether authenticate()
is successful before using login()
来源:https://stackoverflow.com/questions/7910769/extending-usercreationform-to-include-email-first-name-and-last-name