我在项目中使用了以下变体:
# models.py
import random
from django.conf import settings
from django.db import models
def generate_activation_code():
return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
class ActivationCode(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
code = models.CharField(max_length=6, default=generate_activation_code)
# views.py
from django.http import Http404
def register_user(request):
# create your `new_user` however you see fit
code = ActivationCode.objects.create(user=new_user)
send_mail(
'Activate Your Account',
'Here is the activation code: %s' % code,
'from@example.com',
[user.email]
)
render(request, 'activation_sent.html')
def check_activation_code(request, code):
try:
ActivationCode.objects.get(code=code)
# ... All set, activate & login the user, & delete the activation code
except ActivationCode.DoesNotExist:
raise Http404
return render(request, 'welcome.html')
增强功能可能包括为您在视图中签入的内容添加到期日期ActivationCode
,和/或清理旧代码的管理作业。