I write some code to register a user. In my fonction "register(request)", Before i do email verification i save the user and he is saved in the database but he is not active. Then i use this user to activate him in my function "activate(request)" and i activate the user. But there is a problem, if the user put a wrong or not email, he will be saved in database, and this can take useless memory space in database. And the other problem is that if the user want to correct his informations on registration page, he will not be able to do that because his username and email already exists in database.
def register(request):
registered = False
if request.method == 'POST':
form = UserForm(data=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 = 'Activez votre compte acquisitor.'
message = render_to_string('users/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()
return render(request, 'users/mail_registration.html')
else:
print(form.errors)
else:
form = UserForm()
return render(request, 'users/registration.html', {'user_form': form,
'registered': registered})
def activate(request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend'):
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
registered = True
user.save()
login(request, user, backend)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Lien d'activation invalide")
Aucun commentaire:
Enregistrer un commentaire