Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. User model custom field । Registration Login Logout Custom Html

User model custom field । Registration Login Logout Custom Html

Create a new Django project and app:

django-admin startproject custom_auth_project
cd custom_auth_project
python manage.py startapp custom_auth_app

#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'custom_auth_app',
]

# custom_auth_app/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # Add any additional fields you want for your user model here
    bio = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.username

যখন কাস্টম ইউজার মডেল ব্যবহার করবো তখন settings.py ফাইলে বলে দিতে হবে যে কোনটা ইউজার মডেল হিসাবে ব্যবহার করতে চাচ্ছি তা না হলে মাইগ্রেশন করার সময় এরর শো করবে।

#settings.py
AUTH_USER_MODEL = "custom_auth_app.CustomUser"
# custom_auth_app/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser

class CustomUserRegistrationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'password1', 'password2')
    # Use custom widgets to hide error messages
    username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email address'}))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password confirmation'}))

        

class CustomUserLoginForm(AuthenticationForm):
    username = forms.CharField(
        max_length=254,
        widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control', 'required': 'required'})
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', 'required': 'required'})
    )

from django.shortcuts import render

# custom_auth_app/views.py
from django.contrib.auth import login
from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .forms import CustomUserRegistrationForm, CustomUserLoginForm

class CustomUserRegistrationView(CreateView):
    form_class = CustomUserRegistrationForm
    template_name = 'registration.html'
    success_url = reverse_lazy('login')

    def form_valid(self, form):
        user = form.save()
        login(self.request, user)
        return super().form_valid(form)

class CustomUserLoginView(LoginView):
    form_class = CustomUserLoginForm
    template_name = 'login.html'



from django.contrib.auth.decorators import login_required
@login_required
def profile_view(request):
    # Add logic to fetch and display the user's profile information
    return render(request, 'profile.html')

<!-- custom_auth_app/templates/login.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <!-- Add your CSS and font-awesome library (adjust paths as needed) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

</head>
<body>
    <form method="post" class="row g-4">
        {% csrf_token %}
            <div class="login-page bg-light">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-10 offset-lg-1">
                          <h3 class="mb-3">Registration Now</h3>
                            <div class="bg-white shadow rounded">
                                <div class="row">
                                    <div class="col-md-7 pe-0">
                                        <div class="form-left h-100 py-5 px-5">
                                         
                                                    <div class="col-12">
                                                        <label>Username<span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <div class="input-group-text"><i class="fa fa-user"></i></div>
                                                            {{ form.username}}                                                            </div>
                                                    </div>
            
                                                    <div class="col-12">
                                                        <label>Password<span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <div class="input-group-text"><i class="fa fa-lock"></i></div>
                                                            {{ form.password1 }}                                                        </div>
                                                    </div>

                                                    <div class="col-12">
                                                        <label>Confirm Password<span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <div class="input-group-text"><i class="fa fa-lock"></i></div>
                                                            {{ form.password2 }}                                                        </div>
                                                    </div>

                                                    <div class="col-sm-6">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="inlineFormCheck">
                                                            <label class="form-check-label" for="inlineFormCheck">Remember me</label>
                                                        </div>
                                                    </div>
            
                                                    <div class="col-sm-6">
                                                        <a href="{% url 'password_reset' %}" class="float-end text-primary">Forgot Password?</a>
                                                    </div>
            
                                                    <div class="col-12">
                                                        <button type="submit" class="btn btn-primary px-4 float-end mt-4">Registration</button>
                                                    </div>
                                            
                                        </div>
                                    </div>
                                    <div class="col-md-5 ps-0 d-none d-md-block">
                                        <div class="form-right h-100 bg-primary text-white text-center pt-5">
                                            <i class="bi bi-bootstrap"></i>
                                            <h2 class="fs-1">Welcome New Member!!!</h2>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </form>


    <!-- Add your JavaScript and Bootstrap CSS/JS (if needed) here -->
</body>
</html>
<!-- custom_auth_app/templates/login.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <!-- Add your CSS and font-awesome library (adjust paths as needed) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

</head>
<body>
    <form method="post" class="row g-4">
        {% csrf_token %}
            <div class="login-page bg-light">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-10 offset-lg-1">
                          <h3 class="mb-3">Login Now</h3>
                            <div class="bg-white shadow rounded">
                                <div class="row">
                                    <div class="col-md-7 pe-0">
                                        <div class="form-left h-100 py-5 px-5">
                                         
                                                    <div class="col-12">
                                                        <label>Username<span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <div class="input-group-text"><i class="fa fa-user"></i></div>
                                                            {{ form.username}}                                                            </div>
                                                    </div>
            
                                                    <div class="col-12">
                                                        <label>Password<span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <div class="input-group-text"><i class="fa fa-lock"></i></div>
                                                            {{ form.password }}                                                        </div>
                                                    </div>
            
                                                    <div class="col-sm-6">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="inlineFormCheck">
                                                            <label class="form-check-label" for="inlineFormCheck">Remember me</label>
                                                        </div>
                                                    </div>
            
                                                    <div class="col-sm-6">
                                                        <a href="{% url 'password_reset' %}" class="float-end text-primary">Forgot Password?</a>
                                                    </div>
            
                                                    <div class="col-12">
                                                        <button type="submit" class="btn btn-primary px-4 float-end mt-4">login</button>
                                                    </div>
                                            
                                        </div>
                                    </div>
                                    <div class="col-md-5 ps-0 d-none d-md-block">
                                        <div class="form-right h-100 bg-primary text-white text-center pt-5">
                                            <i class="bi bi-bootstrap"></i>
                                            <h2 class="fs-1">Welcome Back!!!</h2>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </form>


    <!-- Add your JavaScript and Bootstrap CSS/JS (if needed) here -->
</body>
</html>

    path('accounts/profile/', views.profile_view, name='profile'),  
    path('register/', views.CustomUserRegistrationView.as_view(), name='register'),  
    path('login/', views.CustomUserLoginView.as_view(), name='login'),  

login redirect

# custom_auth_app/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def profile_view(request):
    # Add logic to fetch and display the user's profile information
    return render(request, 'profile.html')



# custom_auth_app/urls.py
from django.urls import path
from .views import profile_view  # Import your profile view

urlpatterns = [
    # ... other URL patterns ...
    path('accounts/profile/', profile_view, name='profile'),  # Replace with your profile view and URL
]


# settings.py
LOGIN_REDIRECT_URL = 'accounts/profile/'  # Replace with the actual URL path to your profile page

logout

# custom_auth_app/urls.py
from django.urls import path
from django.contrib.auth.views import LogoutView

urlpatterns = [
    # ... other URL patterns ...
    path('logout/', LogoutView.as_view(), name='logout'),
]


## custom_auth_app/templates/profile.html -->
##  ... other profile content ... -->
<a href="{% url 'logout' %}">Logout</a>



# settings.py
LOGOUT_REDIRECT_URL = '/'  # Replace with the URL path to redirect to after logout

Forgot Password

from django.contrib.auth.views import (
    PasswordResetView,
    PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView,
)


urlpatterns = [

    
    path('password_reset/', PasswordResetView.as_view(), name='password_reset'),
    path('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
    path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('reset/done/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),

    # Add other URLs as needed
]
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'olee.techs@gmail.com'
EMAIL_HOST_PASSWORD = 'jzsbfkxvmxiabwow' #past the key or password app here
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'from olee tech'

How can we help?