Beranda

Blog

Kerjasama

Forum

Informasi

Aplikasi

Tools

Pelayanan

Beranda

Blog

Kerjasama

Forum

Informasi

Aplikasi

Tools

Pelayanan

contoh code register dan login di Django, termasuk form, views, URL routing, dan template sederhana:

contoh code register dan login di Django, termasuk form, views, URL routing, dan template sederhana:

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']

2. Views: 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')

3. URL Routing: 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
]

4. Template HTML Sederhana

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>

5. Contoh Home View (Opsional)

# 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>
Topik : Pengetahuan Artikel
Dibaca : 29 kali

Komentar (0)

Kami

Flask

Django

Python

Linux

Kecerdasan

Ketentuan

Pencarian

Kami

Flask

Kecerdasan

Django

Python

Linux

Ketentuan

Pencarian

Copyright PythonesiaORG 2023