Home > Net >  Django Authentication Application
Django Authentication Application

Time:03-08

I've just started to the django and got a little lost in between various doumentations and outdated tutorials.

What I want to achieve is to create a simple dashboard application that also contains some backend scripts to integrate various apis most of them are open API's like weather API's , calendar API's etc just for learning.

But I need to create a login page for the application and current tutorials for the authentication mosule of django is a little bit cunfusing as it never gives me how to implemelent a login form to the auth backend. I need a little bir more simple documentation for that.

Is there anyone able to help me on that. I know the question is not code related but still any help will be appriceated. Most of findings from my previous searches are outdated and implementing those methods are often causes errors like non-existent templates etc...

Meanwhile I'll be also checking the offical documentation.

Thank you.

CodePudding user response:

So it depends what view you use to handle login as there are two types of views Class based and function based. I use Function based so I shall explain you with that.

First you should set up an html page that will have the form to take the details of the username and password. I assume you know how to do that and how to handle the form in the html (if not please comment is shall explain you that too). So now the view that will handle the login authentication is below

from django.contrib.auth import login,authenticate

def login_page(request):
   if request.method == 'POST':
        username =  request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username= username, password= password)
        if user is not None:
            login(request, user)
            return redirect('any_page_you_want_to_send_the_user')
   else:
       return render(request, 'login.html')

So what the above code does is that it accepts a POST request that you send from your login form and then it gets the username and password from that form. Then it uses the django's authenticate function to authenticate the user. It then checks if the there is actually an user or it is None(doesn't exists). And if the condition is true, it logs in the current user.

  • Related