Skip to main content

User Authentication in Django (Login, Register, Logout)

 User Authentication in Django (Login, Register, Logout)


🧠 Introduction

Modern web applications lo User Authentication chala important concept.
Simple ga cheppali ante, website lo users ni identify cheyadam, secure access ivvadam.

Manam daily use chese apps like:

  • Social media
  • E-commerce websites
  • Blogging platforms

anni authentication system meeda depend ayi untayi.


🔐 What is User Authentication?

User Authentication ante:

👉 User evaro verify cheyadam
👉 Valid credentials (username, password) check cheyadam
👉 Correct ayite access ivvadam

Idi security backbone ani cheppachu.


⚙️ Main Components

1️⃣ Register (Sign Up)

Kotha user account create chesukuntadu.

👉 User details:

  • Username
  • Email
  • Password

Store avutayi database lo.


2️⃣ Login

Already account unna user login avutadu.

👉 System:

  • Username/password verify chestundi
  • Correct ayite login allow chestundi

3️⃣ Logout

User session ni close cheyadam.

👉 Security kosam:

  • Logout taruvata restricted pages access avvu

🏗️ How Django Handles Authentication

Django lo built-in ga powerful authentication system undi.

👉 Features:

  • User model ready ga untundi
  • Password hashing automatic
  • Login/logout handling easy

Manam scratch nundi build cheyyalsina avasaram ledu — Django already provide chestundi.


🔄 Authentication Flow

Simple flow ila untundi:

  1. User register chestadu
  2. Credentials database lo store avutayi
  3. User login attempt chestadu
  4. System verify chestundi
  5. Valid ayite session create avutundi
  6. Logout ayite session destroy avutundi

💡 Why Authentication is Important?

👉 Unauthorized access prevent cheyadaniki
👉 User-specific data protect cheyadaniki
👉 Personalized experience ivvadam kosam
👉 Secure web application build cheyadaniki


🚀 Real-Time Use Case (Mana Blog Project)

Mana Django blog project lo:

👉 Only logged-in users:

  • Blog create cheyali
  • Edit cheyali
  • Delete cheyali

👉 Public users:

  • Blogs chudachu (read-only)

🔥 Conclusion

User Authentication ane di every web application ki must-have feature.

Django tho:

  • Easy implementation
  • Secure system
  • Scalable architecture

Next step lo manam:

👉 Full Login, Register, Logout code build cheddam
👉 Blog ni user-based system ga marchadam 🚀


📢 Call To Action

“Code cheyyadam tho ne nerchukovali 💻🔥”


views.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from .forms import SignupForm, LoginForm

# SIGNUP
def signup_view(request):
    form = SignupForm()

    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.save()
            return redirect('login')

    return render(request, 'signup.html', {'form': form})


# LOGIN
def login_view(request):
    form = LoginForm()

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login(request, form.user)
            return redirect('dashboard')

    return render(request, 'login.html', {'form': form})


# LOGOUT
def logout_view(request):
    logout(request)
    return redirect('login')



🌐 urls.py

from django.urls import path
from . import views

urlpatterns = [
path('signup/', views.signup_view, name='signup'),
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
]


🎨 HTML Templates

🧩 base.html

<!DOCTYPE html>
<html>
<head>
    <title>Auth System</title>
</head>
<body>

<nav>
    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }}</p>
        <a href="{% url 'logout' %}">Logout</a>
    {% else %}
        <a href="{% url 'login' %}">Login</a>
        <a href="{% url 'signup' %}">Signup</a>
    {% endif %}
</nav>

<hr>

{% block content %}{% endblock %}

</body>
</html>

📝 signup.html


{% extends 'base.html' %}

{% block content %}
<h2>Signup</h2>

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

    <input type="text" name="username" placeholder="Username"><br><br>
    <input type="email" name="email" placeholder="Email"><br><br>
    <input type="password" name="password" placeholder="Password"><br><br>
    <input type="password" name="confirm_password" placeholder="Confirm Password"><br><br>

    <button type="submit">Signup</button>
</form>

<p>Already have account? <a href="{% url 'login' %}">Login</a></p>

{% if form.errors %}
    <p style="color:red;">{{ form.errors }}</p>
{% endif %}
{% endblock %}


🔐 login.html


{% extends 'base.html' %}

{% block content %}
<h2>Login</h2>

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

    <input type="text" name="username" placeholder="Username"><br><br>
    <input type="password" name="password" placeholder="Password"><br><br>

    <button type="submit">Login</button>
</form>

<p>Don't have account? <a href="{% url 'signup' %}">Signup</a></p>

{% if form.errors %}
    <p style="color:red;">Invalid login details</p>
{% endif %}
{% endblock %}


📊 dashboard.html


{% extends 'base.html' %}

{% block content %}
<h2>Dashboard</h2>

<p>Welcome {{ user.username }} 🎉</p>
<p>You are successfully logged in 🔐</p>
{% endblock %}


🔒 (Protect Dashboard)


from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

Comments

Popular posts from this blog

“Password Reset in Django – Complete Guide”

  Password Reset in Django – Complete Guide 🔐 Introduction Web applications lo Password Reset feature chala important. User password marchipothe, easy ga recover chesukovadaniki use avutundi. Real-time lo: Gmail Facebook Instagram anni password reset system use chestayi. ⚙️ How Password Reset Works? 👉 Step-by-step flow: User “Forgot Password” click chestadu Email enter chestadu System reset link send chestundi User link open chestadu New password set chestadu 👉 Idi secure ga untundi because: Token based verification Time limit untundi ⚙️ Django Password Reset Code 1️⃣ settings.py (EMAIL Setup) # settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 👉 Dev lo console lo email link chupistundi 👉 Production lo Gmail SMTP use cheyachu 2️⃣ urls.py from django . urls import path from django . contrib . auth import views as auth_views urlpatterns = [ path ( 'password-reset/' , auth_v...

Python Day 5 – If Else Conditions

  🐍 Python Day 5 – If Else Conditions 🧠 Introduction 🐍 Python Day 5 – If Else Conditions Ippati varaku manam operators nerchukunnam. I roju manam decision making (If-Else) nerchukundam. 👉 Program lo condition base chesi decisions tiskovadaniki use avutundi 💡 Example: Age 18 kanna ekkuva unte → eligible Lekapothe → not eligible 🔹 Basic If Condition age = 20 if age > 18 : print ( "Eligible" ) 🔹 If-Else Condition age = 16 if age >= 18 : print ( "Eligible" ) else : print ( "Not Eligible" ) 🔹 If-Elif-Else marks = 75 if marks >= 90 : print ( "Grade A" ) elif marks >= 60 : print ( "Grade B" ) else : print ( "Grade C" ) 🧪 Real Example (User Input) age = int ( input ( "Enter your age: " )) if age >= 18 : print ( "You can vote ✅" ) else : print ( "You cannot vote ❌" ) ⚠️ Important Points 👉 Indentation (space) very import...

Python Day 8 – Lists

  🧠 Introduction 🐍 Python Day 8 – Lists Ippati varaku manam functions nerchukunnam. Eroju manam Lists gurinchi nerchukundam. 👉 List ante multiple values ni okesari store cheyadaniki use avutundi 💡 Example: Shopping items list laga 📦 🔹 Create List numbers = [ 1 , 2 , 3 , 4 , 5 ] names = [ "Manju" , "Ravi" , "Kiran" ] 🔹 Access List (Index) print ( numbers [ 0 ]) # 1 print ( names [ 1 ]) # Ravi 👉 Index always 0 nundi start avutundi ⚠️ 🔹 Add Elements numbers . append( 6 ) print ( numbers ) 🔹 Remove Elements numbers . remove( 3 ) print ( numbers ) 🔹 Loop Through List for i in numbers : print ( i ) 🔹 List Length print ( len ( numbers )) 🔹 Slicing print ( numbers [ 1 : 4 ]) 🧪 Real Example marks = [ 80 , 90 , 75 , 60 ] for m in marks : if m >= 75 : print ( "Pass:" , m ) 🎯 Mini Practice names = [ "A" , "B" , "C" ] names . append( "D...