我正在尝试在django应用中实现基于电子邮件验证的身份验证系统。我真正想要的是,电子邮件链接必须在一段时间后失效。即使用户单击它,该链接也不起作用,并且应该从数据库中删除该用户。该怎么做?
forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password',]
def clean_email(self):
email = self.cleaned_data['email']
print('email cleaned data: ' + self.cleaned_data['email'])
try:
User.objects.get(email=email)
raise forms.ValidationError('Email already exists.')
except User.DoesNotExist:
return email
views.py:
def register(request):
form = UserForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
# username = form.cleaned_data['username']
# password = form.cleaned_data['password']
# user.set_password(password)
user.save()
# user = authenticate(username=username, password=password)
# if user is not None:
# if user.is_active:
# login(request, user)
# return render(request, 'set_goals/index.html')
# context = {
# "form": form,
# }
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('registration/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
# email.send()
user.email_user(mail_subject,message)
return HttpResponse('Please confirm your email address to complete the registration')
context = {
"form": form,
}
return render(request, 'set_goals/register.html', context)
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.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)
# return redirect('home')
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
else:
return HttpResponse('Activation link is invalid!')
如何使链接过期?或在给定时间后单击链接,如何从数据库中删除用户?请帮忙!