Django Form fields disappearing after redirect to login page

Question:

I am using a Django form for a user login page. When the user has an incorrect login, it goes back to the login page. However, when it does this, the form input fields are gone, and the user can’t enter anything, because the inputs just… aren’t there. Note that it displays and functions correctly when I click on the login button in the navbar that goes to "login". It’s just after the postlogin view is run that the inputs disappear.

After I run the postlogin view, it looks like this:

what it looks like after redirecting to login page again from postlogin

It’s supposed to look like this:

what it looks like when clicking on Login in the navbar

Here is my login and my post login view:

def login(request):
    # Rendering login page
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/login.html',
        {
            'title': 'Login',
            'message': 'Login to your account',
            'year': datetime.now().year,
            'form':form
        }
    )

def postlogin(request):
    email=request.POST.get('email')
    pasw=request.POST.get('password')
    try:
        # if there is no error then signin the user with given email and password
        user = authe.sign_in_with_email_and_password(email, pasw)

    except:
        message="Invalid credentials!"
        # return to login page if password and email was invalid
        return render(request,"app/login.html", {'message':message, 'current_user': authe.current_user})

    # set current session with user token
    session_id=user['idToken']
    request.session['uid']=str(session_id)


    return render(request,"app/home.html", {"email":email, 'current_user': authe.current_user})

Here is my urls.py

from datetime import datetime
from django.urls import path
from django.contrib import admin
from django.contrib.auth.views import LoginView, LogoutView
from app import forms
from app import views


urlpatterns = [
    path('', views.home, name='home'),
    path('contact/', views.contact, name='contact'),
    path('about/', views.about, name='about'),
    path('login/',
         LoginView.as_view
         (
             template_name='app/login.html',
             authentication_form=forms.BootstrapAuthenticationForm,
             extra_context=
             {
                 'title': 'Log in',
                 'year' : datetime.now().year,
             }
         ),
         name='login'),
    path('postlogin/', views.postlogin, name='postlogin'),
    path('postsignup/', views.postsignup, name='postsignup'),
    #path('logout/', LogoutView.as_view(next_page=''), name='logout'),
    path('logout/', views.logout, name='logout'),
    path('admin/', admin.site.urls),
]

Here is my forms.py:

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _

class BootstrapAuthenticationForm(AuthenticationForm):
    """Authentication form which uses boostrap CSS."""
    email = forms.CharField(max_length=254,
                               widget=forms.TextInput({
                                   'class': 'form-control',
                                   'placeholder': 'Email'}))
    password = forms.CharField(label=_("Password"),
                               widget=forms.PasswordInput({
                                   'class': 'form-control',
                                   'placeholder':'Password'}))

Here is my login.html


{% block content %}

<h2>{{ title }}</h2>

{% if current_user %} 
<form id="logoutForm" action="/logout/" method="post" class="navbar-right">
    {% csrf_token %}
    <ul class="nav navbar-nav navbar-right">
        <li><span class="navbar-brand">Hello {{ user.username }}!</span></li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
</form>

{% else %}

<ul class="nav navbar-nav navbar-right">
    <li><a href="/login/">Log in</a></li>
</ul>

{% endif %}

<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            <form action="/postlogin/" method="post" class="form-horizontal">
                {% csrf_token %}
                <h4>Use a local account to log in.</h4>
                <hr />
                <div class="form-group">
                    <label for="id_username" class="col-md-2 control-label">Email</label>
                    <div class="col-md-10">
                        {{ form.email }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="id_password" class="col-md-2 control-label">Password</label>
                    <div class="col-md-10">
                        {{ form.password }}
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="hidden" name="next" value="/" />
                        <input type="submit" value="Log in" class="btn btn-default" />
                    </div>
                </div>
                {% if form.errors %}
                <p class="validation-summary-errors">Please enter a correct user name and password.</p>
                {% endif %}
            </form>
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm"></section>
    </div>
</div>

{% endblock %}


{% block scripts %}

    {% load staticfiles %}
<script src="{% static 'app/scripts/jquery.validate.min.js' %}"></script>

{% endblock %}
Asked By: thewaterbuffalo

||

Answers:

You can use the Django redirect function to redirect to another view or url so:

from django.shortcuts import redirect

def postlogin(request):
    email=request.POST.get('email')
    pasw=request.POST.get('password')
    try:
        user = authe.sign_in_with_email_and_password(email, pasw)

    except:
        message="Invalid credentials!"
        # return to login function if password and email was invalid
        return redirect(login) #or return redirect('/some/url/')
Answered By: ilyasbbu