Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlx Ki
Python Web Development Techdegree Graduate 14,822 PointsMy automatic login stopped working after adding custom User.
Hi, Kenneth Love !
I added some code to SignUp view to login users automatically right after signing up.
class SignUp(generic.CreateView):
form_class = forms.UserCreationForm
success_url = reverse_lazy('posts:all')
template_name = "accounts/signup.html"
def form_valid(self, form):
valid = super().form_valid(form)
username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')
user = authenticate(username=username, password=password) # This returns None
login(self.request, user)
return valid
It worked well. But.
After we added a custom User model, when I Sign Up a new user it creates new user and then returns 500 error on this line:
login(self.request, user)
Here is an error:
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
AttributeError: 'AnonymousUser' object has no attribute '_meta'
"POST /accounts/signup/ HTTP/1.1" 500 97428
What would be the way to solve it?
UPDATE: For some reason this line from form_valid(self, form) doesn't work any more:
user = authenticate(username=username, password=password) # This returns None
2 Answers
Kenneth Love
Treehouse Guest TeacherCan you post your custom user model?
Kenneth Love
Treehouse Guest TeacherHmm, I don't see anything that looks off. You've set AUTH_USER_MODEL
in settings.py
, yeah?
Alx Ki
Python Web Development Techdegree Graduate 14,822 PointsYes, sure. It creates user in database correctly. Newly created user is active, and can log in with LoginView.
Maybe authenticate() expects email and password?
Kenneth Love
Treehouse Guest TeacherAh, yeah, you should be doing, effectively authenticate(username=form.email, password=form.password1)
(fake code, but you get what I mean).
Alx Ki
Python Web Development Techdegree Graduate 14,822 PointsIt works! Feel so good! ^_^ Thank You!
Alx Ki
Python Web Development Techdegree Graduate 14,822 PointsWorks with:
def form_valid(self, form):
valid = super().form_valid(form)
email, password = form.cleaned_data.get('email'), form.cleaned_data.get('password1')
user = authenticate(email=email, password=password)
login(self.request, user)
return valid
Alx Ki
Python Web Development Techdegree Graduate 14,822 PointsAlx Ki
Python Web Development Techdegree Graduate 14,822 PointsHere it is: