Django-User Login and Logout Django by Ravinder Nath Rajotiya - January 11, 2022January 15, 20220 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle User Login and Logout:TestingPage not found (404)Solution to this problem :-Django administrationLogged outDjango administrationSo finally what we want:Making updates in navigation barMaking user to access restricted page User Login and Logout: In this tutorial we are going to see how to create the authentication system for our Django applications so that the users can login, logout. Also the users need to be logged in, in order to access certain pages. The registration page created in the Django- Admin and Users registration post was used only by admin, but the users were not able to login. So, we have to create a login page for the frontend where users will be able to register, login or logout. Django has lot of functionality taking care for us at the backend. So, we get started with using the default LoginView If you want the users to login and have access to certain pages/database from the application then we need to create the login and logout page. In this tutorial you are going to learn how to create these pages. So first we have to import the LoginView and LogoutView into our url model Step-1 – import LoginView and LogoutView in project urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path(‘admin/’, admin.site.urls), path(‘register/’, user_views.register, name=’register’), path(‘login/’,auth_views.LoginView.as_view(), name=’login’), path(‘logout/’,auth_views.LogoutView.as_view(), name=’logout’), path(‘blogApp/’, include(‘blogApp.urls’)), ] LogoutView and LoginView are class base built-in views, we could also create our own views as well. Here. I would like to mention that whenever you are to import views, you should import them using as auth_views or users_views etc that way the names will not collide, then create the paths for those views as shown in above code. If you run the server now and try to load the ‘localserver:8000/login’ page you will see the error TemplateDoesNotExist at registration/login.html/ These django error messages are very useful during debug because directs us as to what changes are to be done in order to fix the things to be working. This error is because we have not yet created the template ‘login.html’ inside our users folder of the ‘users’ app. We could have created a directory registration inside the template and created the login template there, but as an alternate, let us tell django where to look for the template. This can be fixed by passing the template_name with the as_View inside the urlpatterns list as shown below: path(‘login/’, auth_views.LoginView.as_view(template_name=’users/login.html’),name=’login’), path(‘logout/’, auth_views.LogoutView.as_view(template_name=’users/logout.html’),name=’logout’) reload the page, you still get error- TemplateDoesNotExist at /login/ users/login.html Now the error points that it is looking for the login template inside the users directory. Step-2: So, Create login.html template in the users folder Copy the code from the register.html, paste in login.html page and make following changes in the login.html template. <legend class=“border-bottom mb-4”> LOG In </legend> <div class=“form-group”> <button class=“btn btn-outline-info” type=“submit” name=“button”>Sign in</button> </div> <small class=“text-muted”> Do you need an account? <a class=“ml-2” href=“{% url ‘register’%}”>Click To Register</a></small> Also go back to register.html page and enter the url in the href section of the page as: <small class=“text-muted”> Already have an account? <a class=“ml-2” href=“{% url ‘login’%}”>Sign in</a> </small> Testing Save the login.html and register.html files and reload the login template in the browser with localhost:8000/login as the url. The login page opens and also has somewhat functionality We find that the page is having some functionality, i.e. if we give a wrong username and password, it gives us a correct message that user doesnot exist or wrong password. But,if login with correct credentials, we get an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ It means it is looking foa route that doesn’t exist, it is not that the template doesn’t exist but it is ltrying to access an URL that doesn’t have a view. Solution to this problem :- Create the profile, as by default django is trying to redirect the user to the account rofile. OR redirect path as given in the settings.py inside the project folder. For this, we update the LOGIN_REDIRECT_URL at the end of settings.py file as: # Static files (CSS, JavaScript, Images) STATIC_URL = ‘/static/’ LOGIN_REDIRECT_URL=’home’ Now reload the login.html template as localhost:8000/login. You will find the page working well and redirects to the home page. We can thus make a user to get directed to any page as needed. There is no visual feedback righnow, but if you now load the admin page as localhost:8000/admin, you find that you are already logged in as an admin. Making user to redirect to login page after they login let us now make changes in the register view inside the views.py of users app as: messages.success(request,f’your account has been created, you are redirected to login page’) return redirect(‘login’) Let us also change the route of the register page inside urls.py of main project so that the users are redirected to the login page after they login. path(‘logout/’, auth_views.LogoutView.as_view(),name=’logout’), # default as_view function Now reload the logout template as localhost:8000/logout, what you notice is you are directed to the correct page, but it has the Django default header. and looks like a Django admin page. Django administration Home Logged out Thanks for spending some quality time with the Web site today. Log in again Also if we now login with link on this page, we are directed to the admin login page Django administration Username : XXXXXXXXXXX Passwod : XXXXXXXXXXXX Login : This is not what we want. So finally what we want: We wish to have our own header and an authentication system that works for every one at the fron-end of the website and doesn’t expose them to the admin section. So, we have to create a logout template inside the template/users folder and tell logout to use that template just like what we did with login.html. First let us tell logout view that we wish to look at a a different template. This is by changing as_View function in the urls.py in main function as: path(‘logout/’, auth_views.LogoutView.as_view(template_name=’users/logout.html’),name=’logout’) and the create a logout.html template inside template/users directory in the users app. as: {%extends ‘blog/base.html’ %} {% block content %} <h2> You have been logged out </h2> <div class=“border-top pt-3”> <small class=”text-muted”> <a href=”{% url ‘login’ %}”>Login Again</a> </small> </div> {% endblock %} Making updates in navigation bar Every thing now works fine, we are able to login and logout with proper views. Let us also make a change so that when we are logged-in we see the only logout tab on menu bar, and when logged out we see only the log in and register tabs. update navbar.html as – {% if user.is_authenticated %} <a class=“nav-link” href=“{% url ‘logout’%}”>logout</a> {% else %} <a class=“nav-link” href=“{% url ‘login’%}”>login</a> <a class=“nav-link” href=“{% url ‘register’%}”>register</a> {% endif %} Now your views look fine Making user to access restricted page It is also required that restricted pages be accessed only to logged-in users, say you need to edit a profile, then the user must be logged-in. It will very risky to permit anyone edit somebody profile. So it should be mandetory to log-in for restricted pages. How to have access to such restricted pages- step-1: Create user view inside the users view.py as- def profile(request): return render(request, ‘user/profile.html’) step-2: create a profile template in template/users folder {% extends ‘blog/base.html’ %} {% block body %} <h1>{{ user.username}}</h1> {% endblock %} user is not something that we have to create but is inbuilt inside the Django that represents the current logged in User step-3: Update route in main project urls.py path(‘profile/‘, user_views.profile, name=‘profile’), step-4: update route in navigation file navbar.html in the template/blog inside the blogApp {% if user.is_authenticated %} <a class=“nav-link” href=“{% url ‘profile’%}”>Profile</a> <a class=“nav-link” href=“{% url ‘logout’%}”>logout</a> {% else %} So now when we click on the profile tab in the navigation bar, our profile view should open in the browser. and yes that is ok, but the problem is, when you logout and access the profile page directly by typing in the address bar, You don’t get any feedback as what should be here, but we wand a message to appear that log-in to access this page step-1: add import login_required decorator from django.contrib.auth.decorators import login_required step-2 above the def profile function, append @login_required step-3 in the settings.py, at the end append LOGIN_URL=’login’ Share on Facebook Share Send email Mail Print Print