0
votes

I'm new in Django. I tried to create an auto-login after registration users. But I got fail. I created a custom auth backend for username and password asuthentification.

class EmailBackend(object):
def authenticate(self, username=None, password=None):
    user_cls = get_user_model()
    try:
        user = user_cls.objects.get(email=username)
        if user.check_password(password):
            return user
    except user_cls.DoesNotExist:
        return None


def get_user(self, user_id):
    user_cls = get_user_model()
    try:
        return user_cls.objects.get(pk=user_id)
    except user_cls.DoesNotExist:
        return None

AUTHENTICATION_BACKENDS = (
    'user.back_auth.EmailBackend',
    'django.contrib.auth.backends.ModelBackend',
)

I try to make autologin after registration for users:

def register(request):
if request.method == 'POST':
    user_form = UserForm(request.POST)
    if user_form.is_valid():
        user = user_form.save()
        messages.info(request, "Thanks for registering. You are now logged in.")
        user = authenticate(username=request.POST['username'],
                            password=request.POST['password'])
        login(request, user)
        return HttpResponseRedirect("/")
else:
    user_form = UserForm()
    return render(request,
            'user/register.html',
            {'user_form': user_form } )

But, I'm getting the next:

AttributeError at /user/register/ 'AnonymousUser' object has no attribute 'backend'

2
Do you have any save method in UserForm or Can you make sure user is created or what ? And also tell how password looks like ( plaintext or hash ) ?Raja Simon
I have no other save method in UserForm. And password is plaintextuser4251615
Why do you even have a custom auth backend? It isn't doing anything different from the standard one.Daniel Roseman
It's allow use email and username for authitificationuser4251615
@AleksanderGordienko Tried my answer is that workingRaja Simon

2 Answers

1
votes

Your user creation method is wrong because I assume you are saving user in a plain text.

Two ways...

Method using set_password

Method using create_user

0
votes

My working version:

def register(request):
if request.method == 'POST':
    user_form = UserForm(request.POST)
    if user_form.is_valid():
        user = user_form.save()
        user.set_password(request.POST['password'])
        user.save()
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username,password=password)
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
    messages.info(request, "Thanks for register!")
    return HttpResponseRedirect("/")