Authentication in Django-1

Authentication in Django with MySQL

🔐 Authentication in Django with MySQL

Django comes with a powerful built-in authentication system that handles user login, logout, registration, password management, and access control. This blog post will walk you through the basic setup of Django authentication using MySQL as the database backend.

📌 Prerequisites

  • Python and pip installed
  • MySQL Server running
  • Django installed (pip install django)
  • mysqlclient installed: pip install mysqlclient

🔧 Step 1: Start a Django Project

django-admin startproject myauth

Move into your project folder:

cd myauth

🛠️ Step 2: Configure MySQL Database in settings.py

Update your DATABASES section like this:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'myauth_db',
    'USER': 'your_mysql_user',
    'PASSWORD': 'your_mysql_password',
    'HOST': 'localhost',
    'PORT': '3306',
  }
}

Now create the database in MySQL:

CREATE DATABASE myauth_db;

🚀 Step 3: Create and Register the App

python manage.py startapp accounts

Add 'accounts' to INSTALLED_APPS in settings.py.

🧑 Step 4: Create Registration and Login Views

In accounts/views.py:

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.contrib.auth.models import User

def register_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = User.objects.create_user(username=username, password=password)
        return redirect('login')
    return render(request, 'register.html')

def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html', {'error': 'Invalid credentials'})
    return render(request, 'login.html')

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

📄 Step 5: Create HTML Templates

templates/register.html:

<form method="post">
  {% csrf_token %}
  <input name="username" placeholder="Username"><br>
  <input name="password" type="password" placeholder="Password"><br>
  <button type="submit">Register</button>
</form>

templates/login.html:

<form method="post">
  {% csrf_token %}
  <input name="username" placeholder="Username"><br>
  <input name="password" type="password" placeholder="Password"><br>
  <button type="submit">Login</button>
  {% if error %}<p style="color:red;">{{ error }}</p>{% endif %}
</form>

🌐 Step 6: Add URL Patterns

In accounts/urls.py:

from django.urls import path
from . import views

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

In myauth/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
]

⚙️ Step 7: Run Migrations and Start Server

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

✅ Test It!

  • Visit http://127.0.0.1:8000/accounts/register/ to create a user
  • Visit http://127.0.0.1:8000/accounts/login/ to login
  • Visit http://127.0.0.1:8000/accounts/logout/ to logout

📚 Useful Links

Post a Comment

0 Comments

Me