[Fixed]-Where should I place the login and logout in Django?

1πŸ‘

You should use some user authentication within one App which you have created, or create one App just for managing accounts.

Since you are a beginner you should take a look at Django-admin user authentication.

https://docs.djangoproject.com/en/1.10/topics/auth/

πŸ‘€renno

0πŸ‘

Your question is not clear as to what you want to place. Is the template files you want to place in or the view function β€œlogout” and β€œlogin”? I assume it has to be the β€œlogin” and β€œlogout” function what you are looking for.

You have to create a views.py file under β€œ[projectname]/apps” folder.

view for login

def login_validate(request):
      if request.method == "POST":
          username = request.POST['username']
          password = request.POST['password']
          user = authenticate(username= username, password= password)
          if user is not None:
             login(request,user)
             return HttpResponseRedirect('/--template name--/')

          else:
             return HttpResponseRedirect('/--template name--/')

       else:
             return HttpResponseRedirect('/--template name--/')

view for logout


    def logout_page(request):
        logout(request)
        return render(request,"logout_page.html",{})

Above are the functions. You will have to add few things in settings.py before doing this.

And also create a urls.py file under apps folder and link it to main urls.py file.

I hope this is clear.

https://docs.djangoproject.com/en/1.10/topics/auth/default/

https://www.youtube.com/watch?v=eMGtdtNR4es

The above links are helpful.

πŸ‘€sushh

0πŸ‘

The answer to the question is quite subjective i.e. varies from project to project, or developer to developer. My suggestions β€˜d be:

  1. As you have asked for the log-in and log-out functions, this means you’ll be handling users for your app – so a good approach β€˜d be to have a users app, and place the functions in users/views.py

  2. For complex system – where you may have different types of users i.e. users, admin_users, partners, etc. You can have separate directory at project root e.g. lib/ and have functions.py in it, keep all the project wide usable functions, utilities in this file.

    projectname]/                  <- project root 
    β”œβ”€β”€ [projectname]/              <- Django root
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ settings/
    β”‚   β”œβ”€β”€ urls.py
    β”‚   └── wsgi.py
    β”œβ”€β”€ myapp/
    β”‚   β”œβ”€ __init__.py
    β”‚   └── view.py
    β”‚
    β”œβ”€β”€ lib/
    β”‚   β”œβ”€ __init__.py
    β”‚   └── functions.py
    β”‚
    β”œβ”€β”€ manage.py
    β”‚
    β”œβ”€β”€ static/
    β”‚   └── GLOBAL STATIC FILES
    └── templates/
        └── GLOBAL TEMPLATES
    
πŸ‘€Nabeel Ahmed

Leave a comment