我按照this tutorial设置了自定义注册表单,该表单需要电子邮件和密码来注册新用户(即没有用户名)。我还跟随this tutorial发送一封带有确认链接的电子邮件,以创建帐户。
然后如何为每个帐户分配用户名?也许在他们的name@domain.com中使用该名称,并在名称末尾添加随机数字字符,以使其与其他已经注册的名称相同的唯一性。
users / models.py
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
my-website / views.py
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from users.models import CustomUser
from django.core.mail import EmailMessage
from random import choice
import string
def index(request):
return render(request, 'index.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
def activate(request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend'):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = CustomUser.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, CustomUser.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user,backend='django.contrib.auth.backends.ModelBackend')
# return redirect('home')
return HttpResponse("Thank you for your email confirmation. You can now "+' <a href="/accounts/login">sign in</a>' + " your account.")
else:
return HttpResponse('Activation link is invalid!')
我还为Google和Facebook设置了oauth,如果可能的话,我也想给使用该用户名登录的任何人分配用户名。 我希望服务器发布ID,以便我知道每个帐户对于服务器都是唯一的,并且在我们的主数据库中也是唯一的。
请让我知道是否需要更多信息!