Home > Back-end >  How to use a Django (Python) Login Form?
How to use a Django (Python) Login Form?

Time:11-20

I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login process canot work and the form is a simple static html form.

I hope you can help me.

HTML:


<form  method="POST">
{% csrf_token %}

                <input type="text" placeholder="account" name="username">
                <br>
             
                <input type="password" placeholder="password" name="password">
                <br>
    
                <button style="margin: 20px;" type="submit">join</button>
            </div>
    
    </div>
    </form>

views.py


def loginuser(request):
if request.method == "POST":
username = request.POST['accountName']
password = request.POST['accountPassword']
user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return views.homepage
        
    
        else:
            return redirect('start')
    
    else:
        return render(request, 'start', {})

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', start),
    path('homepage/', include('homepage.urls'))
] 

homepage urls.py

urlpatterns = [
    path('login/', views.login, name="login"),
    path('register/', views.register, name="register"),
    path('', views.homepage, name="homepage"),
    path('account/', views.account, name="account")
] 

CodePudding user response:

def login(request):
    if request.method = 'POST':
        username = request.POST['username']
        password = request.method = POST['password']

        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request, user)
            return redirect(#User to the dashboard!)
        else:
            message.info(request, "invalid credentials")
            return redirect('login')
    else:
        return render(request, 'login.html')

Login.html:

<form method="POST" action="{% url 'login' %}">
                  {% csrf_token %}
                  <div >
                      <label >Enter Username</label>
                      <input type="text"  name="username" placeholder="Enter Username">
                  </div>

                  <br>
                  <div >
                      <label >Enter Password</label>
                      <input type="password"  name="password" placeholder="Enter Password">
                  </div>
     

                  <br>
                  <button type="submit" >Log in</button>
              </form>

Docs

  • Related