Almost every web app needs user accounts. Django includes a well-tested authentication system, so you should not build password handling yourself. Here is how the pieces fit together.
What Django gives you
- A
Usermodel with username, email and securely hashed passwords. - Ready-made views for login, logout and password reset in
django.contrib.auth.views. - The
@login_requireddecorator to protect pages. request.userin every view and template, so you always know who is logged in.
Login and logout
Include Django’s auth URLs with path("accounts/", include("django.contrib.auth.urls")), then create a template at registration/login.html that renders the form. Set LOGIN_REDIRECT_URL in settings so users land somewhere sensible after logging in. In recent Django versions, logout must be a POST request, so use a small form with a button rather than a plain link.
Signup
Django does not include a signup page, but UserCreationForm does most of the work. A simple view validates the form, saves the user and logs them in with login(request, user). Add your own fields, such as email, by extending the form.
Protecting pages
Add @login_required above any view that needs a logged-in user. For class-based views, use LoginRequiredMixin. In templates, show different links with {% if user.is_authenticated %}.
Good habits
- Never store or print plain-text passwords.
- Use Django’s password validators in settings.
- Keep
DEBUG = Falseand a secret key outside your code in production. - If you need extra profile fields, plan a custom user model at the very start of the project; changing it later is painful.
Next, read Django forms and validation and Django models and migrations.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
