カスタムフォームを持つジャンゴ登録ページ

8198 ワード

フォーム.パイ
from django import forms
class registerCustom(forms.Form):
    username = forms.CharField(widget=forms.TextInput())
    password = forms.CharField(widget=forms.PasswordInput())
    confirm_password = forms.CharField(widget=forms.PasswordInput())
ビューパイ
from .forms import registerCustom
from django.contrib import messages
from django.contrib.auth.forms import User

def register(request):
    if request.method == 'POST':
        form = registerCustom()
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('confirm_password')
        if User.objects.filter(username=username).first():
            messages.error(request,'Username already existed')

        elif len(password) < 8 and len(password2) < 8:
            messages.error(request, 'Your password is too weak at least 8 character up !')
            return redirect('/reg')
        else:
            if password == password2:
                user = User.objects.create(username=username, password=password)
                user.save()
                messages.success(request,'Register successfully !')
                return redirect('/login')
            else:
                messages.error(request,'Password is not match')
                return redirect('/reg')
    else:
        form = registerCustom()
    return render(request,'app/register.html',{'form':form})
レジスタ.HTML
{% block content %}
    <form method="POST">
    {% csrf_token %}
    {{ form }}<br>
    <button type="submit">Sign Up</button>
    <a href="{% url 'login' %}">Login</a>
    </form>
{% endblock %}

URL.パイ
from django.urls import path
from . import views

urlpatterns = [

    path('reg/', views.register),
]