django自定义注册用户
views.py
from django.shortcuts import render
from django.forms import ValidationError
from django.contrib.auth.models import User
from django.views import View
from django.contrib.auth.forms import UserCreationForm, UsernameField
class RegisterViewForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
field_classes = {'username': UsernameField}
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email):
self.add_error('email', ValidationError('邮箱已被注册'))
return email
class RegisterView(View):
def get(self, request):
form = RegisterViewForm()
return render(request, 'registration/register.html', {'form': form})
def post(self, request):
form = RegisterViewForm(data=request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.is_staff = True
new_user.save()
return render(request, 'registration/register_done.html', {'new_user': new_user})
return render(request, 'registration/register.html', {'form': form})
urls.py
path('register/', views.RegisterView.as_view(), name='register'),