﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31367	ImportError error while importing class from auth/mixin to auth/view.	Mehmet İnce	nobody	"While I was doing some tests about discussion related to the [https://groups.google.com/forum/#!topic/django-developers/PUQQUHIxEXQ] , I've realized that it's not possible to import class from django.contrib.auth.mixins to the django.contrib.auth.views .

**Reproduce**

Add following mixin to the auth/mixins.py
{{{
class LoginRequiredExemptMixin(object):
    login_required_exempt = True
}}}

And import it at auth/views.py and use it on one of the CBV. For instance LoginView.

{{{
from django.contrib.auth.mixins import LoginRequiredExemptMixin

class LoginView(SuccessURLAllowedHostsMixin, FormView, LoginRequiredExemptMixin):
    """"""
    Display the login form and handle the login action.
    """"""
}}}

In that case, you will be seeing following ImportError


{{{
  File ""/Users/xxx/PycharmProjects/django/django/contrib/auth/mixins.py"", line 4, in <module>
    from django.contrib.auth.views import redirect_to_login
  File ""/Users/xxx/PycharmProjects/django/django/contrib/auth/views.py"", line 13, in <module>
    from django.contrib.auth.mixins import LoginRequiredExemptMixin
ImportError: cannot import name 'LoginRequiredExemptMixin' from 'django.contrib.auth.mixins' (/Users/mince/PycharmProjects/django/django/contrib/auth/mixins.py)
}}}

**How To Fix**

The reason of the error is mixins.py file have ""django.contrib.auth.views import redirect_to_login"" on line 4. Since the redirect_to_login is only used one place (handle_no_permission  function) in mixin.py we can remove the import from top of the file and call it right before usage of the imported function. For example as follow.

{{{
    def handle_no_permission(self):
        if self.raise_exception or self.request.user.is_authenticated:
            raise PermissionDenied(self.get_permission_denied_message())
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())


}}}

On the other hand, I think why we have **SuccessURLAllowedHostsMixin** class in auth/views.py file even though it's been called Mixin was related that import code in mixin.py too.

By doing this changes we can even move **SuccessURLAllowedHostsMixin** class to the mixins.py file since it's only being used in auth/views.py. That little changes gives us flexibility to import mixings in the feature.




"	Cleanup/optimization	closed	contrib.auth	dev	Normal	wontfix			Unreviewed	1	0	0	0	1	0
