Failure to authenticate User with AuthenticationForm

I’m attempting to create a TemplateView where each subclass renders an AuthenticationForm; subclassing it and naming it UserLoginForm . This gives the User the opportunity to login with their credentials on any page they visit and be redirected to that same page after being successfully authenticated.

When validating UserLoginForm , it fails to authenticate when it reaches form.clean() and raises self.get_invalid_login_error() . The TestCase used to simulate this scenario creates a User, then a POST request with the same credentials is sent. What’s causing the UserLoginForm to invalidate the data passed to it and not finding the User? I’m using the default auth backend: <django.contrib.auth.backends.ModelBackend object at 0x0000019DBF5B3DC8>

Upon debugging, the database has stored the Mock User in the Test Case:

-> user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)                   
(Pdb) from django.contrib.auth.models import User                                                                          
(Pdb) User.objects.all()                                                                                                   
<QuerySet [<User: User>]>                                                                                                  
class TestTopicListMainPage__003(TestCase):
    '''Verify that an anonymous user is logged into their User account'''

    def setUpTestData(cls):
        user = User.objects.create_user("User", 'secretcode') = {
            'username': "User",
            'password': "secretcode"
    def test_topics_listing_login_user(self):
        response =
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "topics/listing.html")
        self.assertContains(response, "Logout")
class UserLoginForm(AuthenticationForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['placeholder'] = field.label.title()
            field.widget.attrs['class'] = "login_text_widget"

class AbstractListingView(TemplateView):

    template_name = "topics/listing.html"

    def get_context_data(self):
        context = super().get_context_data()
        context['topics'] = Topic.objects.all()
        context['search_form'] = SearchForm()
        return context

    def post(self, request):
        context = self.get_context_data()
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            resolver = resolve(request.path)
            login(request, form.get_user())
            return HttpResponseRedirect(reverse(resolver.url_name))
        return self.render_to_response(context)

class TopicsMainPage(AbstractListingView):

    extra_content = {
        'heading': 'Questions',
        'query_links': ['interesting', 'hot', 'week', 'month']

    def get(self, request):
        query = request.GET.get('tab', None)
        context = self.get_context_data()
        if not query:
            if query == "hot":
                previous_days = now - datetime.timedelta(day=3)
            elif query == "week":
                previous_days = now - datetime.timedelta(day=7)
            elif query == "month":
                previous_days = now - datetime.timedelta(day=30)
            now =
            topics = context['topics'].order_by(
                '-views', '-answers__topic', 'posted'
            topics = topics.filter(posted__range=(previous_days, now))[:20]
            context['topics'] = topics
        response = self.render_to_response(context)
        return response

I’m not clear here - is it just that your test is failing, or is it that the form is failing and your test is illustrating that?

When calling create_user, the first two positional arguments are username and email. Password would be the third positional argument. This would explain why you’re unable to log the user in.

user = User.objects.create_user(username="User", password='secretcode')
1 Like