Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST EmailAddress matching query does not exist

I am using django rest-auth and allauth to authenticate users. After successful signup and email verification, I implemented a login view which subclasses rest-auth.views.LoginView like below:

class ThLoginView(LoginView):

    def get(self, request):
        form = CustomUserLoginForm()
        return render(request, "users/login.html", context={"form": form})

with my own form:

class CustomUserLoginForm(AuthenticationForm):
  
    class Meta:
        model = CustomUser
        fields = ('email',)

The problem is that when I login I get this error:

DoesNotExist at /users/login/
EmailAddress matching query does not exist.

Another important thing that I have changed is that I am using email as the signup/login rather than the username:

Settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_UNIQUE_EMAIL = True

and my user model overwrites AbstractBaseUser like so:

class CustomUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(max_length=254, unique=True)
    name = models.CharField(max_length=254, null=True, blank=True)
    username = models.CharField(max_length=254, blank=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'

    EMAIL_FIELD = 'email'

    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

The error seems to suggest that the search algorithm is not looking in the right place for the emails. The user's email is definitely entered since I can oversee this in the admin page. why is this error occurring?

Note: this error also occurs if I use the REST browseable API so it is not linked to my form and template.

Full traceback

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/users/login/

Django Version: 2.2.5
Python Version: 3.7.3
Installed Applications:
['users.apps.UsersConfig',
 'home.apps.HomeConfig',
 'main.apps.MainConfig',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_auth',
 'rest_auth.registration',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount.providers.github',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper
  45.         return bound_method(*args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/views.py" in dispatch
  49.         return super(LoginView, self).dispatch(*args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  505.             response = self.handle_exception(exc)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
  465.             self.raise_uncaught_exception(exc)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in raise_uncaught_exception
  476.         raise exc

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  502.             response = handler(request, *args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/views.py" in post
  103.         self.serializer.is_valid(raise_exception=True)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
  235.                 self._validated_data = self.run_validation(self.initial_data)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
  433.             value = self.validate(value)

File "/Users/ba/venv/project/lib/python3.7/site-packages/rest_auth/serializers.py" in validate
  108.                 email_address = user.emailaddress_set.get(email=user.email)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/ba/venv/project/lib/python3.7/site-packages/django/db/models/query.py" in get
  408.                 self.model._meta.object_name

Exception Type: DoesNotExist at /users/login/
Exception Value: EmailAddress matching query does not exist.
like image 417
bcsta Avatar asked Sep 26 '19 07:09

bcsta


2 Answers

You get this error because the email address you are using to login does not exist in the database table Account Email address. Dj-rest-auth or Django-rest-auth packages creates a table for Email address to track verified users.

You may run into this error when you try to login with users that are created from manage.py commands such as manage.py createsuperuser. Basically, the users created from either django admin console or management command will not create an entry in the Email address table.

To fix this error you may have to create a new entry under Accounts> Email Addresses from admin console or delete the user from Authentication and authorization> Users in admin console and register again using django-rest-auth API endpoint(which will automatically add this entry in Email Address table).

like image 146
Abishek Avatar answered Nov 09 '22 13:11

Abishek


I was facing the same problem when I worked on my custom user model. The reason was that I ran python manage.py makemigrations and python manage.py migrate at the console with the default django user model first. Later, I implemented my custom user model and did the migrations. Django documentation describes the challenge in detail:

Changing AUTH_USER_MODEL after you’ve created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.

This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.

I would suggest to start with a new database, if you can. This is how i solved that issue. Otherwise try to follow this tutorial or this tutorial

like image 40
b0lle Avatar answered Nov 09 '22 14:11

b0lle