1. Form: forms.py
# main/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2']
views.py
# main/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from .forms import RegisterForm
from django.contrib.auth.forms import AuthenticationForm
def register_view(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = RegisterForm()
return render(request, 'register.html', {'form': form})
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
return redirect('login')
urls.py
# main/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'),
path('', views.home_view, name='home'), # Misal ada halaman home
]
templates/register.html
<h2>Register</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Daftar</button>
</form>
templates/login.html
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Masuk</button>
</form>
# main/views.py from django.contrib.auth.decorators import login_required @login_required def home_view(request): return render(request, 'home.html')
templates/home.html
<h2>Halo, {{ request.user.username }}!</h2>
<a href="{% url 'logout' %}">Logout</a>
Copyright PythonesiaORG 2023
Komentar (0)