gpt4 book ai didi

python - 注册django后发送邮件确认

转载 作者:太空狗 更新时间:2023-10-29 18:24:22 28 4
gpt4 key购买 nike

在我的 Django 应用程序中完成注册后,我会发送电子邮件确认。出于安全原因,我需要找出如何在不在用户模型中添加新代码字段的情况下验证我在 url 中发送的代码。到目前为止,我在 url 和经过验证但未验证代码的用户名中发送随机代码。

注册 View

def registrar_usuario_view(request):
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(random.choice(alphabet) for i in range(16))
print code
if request.method == 'POST':
f = RegisterForm(request.POST)
if f.is_valid():
usuario = f.cleaned_data['usuario']
email = f.cleaned_data['email']
clave = f.cleaned_data['clave']
confirmar_clave = f.cleaned_data['confirmar_clave']
captcha = f.cleaned_data['captcha']
u = User.objects.create_user(username = usuario, email = email, password = clave)
u.is_active = False
u.save()
# Mandamos mail de activacion
to = email
html_content = """<h3>Bienvenido Sr/a: %s </h3><p>Para confirmar su registro en el sitio Margonari Servicios Inmobiliarios le solicitamos haga click en el siguiente
<a href='http://localhost:8000/confirmacion/%s/%s'>enlace de confirmacion</a><br><p><b>Gracias por formar parte de Margonari Servicios Inmobiliarios.</b></p><br>
<small>Este es un mensaje enviado automaticamente. Por favor no responda a esta direccion de mail.</small>"""%(usuario, code, usuario)
msg = EmailMultiAlternatives('Administracion Margonari', html_content, 'from@server.com', [to])
msg.attach_alternative(html_content, 'text/html') #Definimos el contenido como html
msg.send() #Enviamos el correo

messages.add_message(request, messages.SUCCESS, """Los datos han sido ingresados correctamente. Le enviamos un correo de confirmacion
a la direccion que nos proporciono. Por favor verifique su casilla de correo no deseado. Muchas gracias.""")
ctx = {'form':f}
return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request))
else:
ctx = {'form':f}
return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request))

f = RegisterForm()
ctx = {'form':f}
return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request))

确认 View

def confirmacion_view(request, code, user):
user = User.objects.get(username = user)
user.is_active = True
user.save()
return HttpResponseRedirect('/')

网址

url(r'^confirmacion/(?P<code>.*)/(?P<user>.*)/$', 'confirmacion_view', name = 'vista_confirmacion'),

最佳答案

Django提供了token创建机制,无需重新发明轮子。由于我不使用基于函数的 View ,而且这里的重点不是重构您的代码(无论如何我都会在 CBV 中这样做),我将只输出一个示例,告诉您如何使用它。

from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes

new_user = User.objects.create_user(username=usuario,
email=email,
password=clave)
new_user.save()
token = default_token_generator.make_token(new_user)
uid = urlsafe_base64_encode(force_bytes(new_user.pk))

然后您可以将 token 通过电子邮件发送给用户, token 网址应如下所示:

url(r'^users/validate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
activationview,
name='user-activation-link')

激活 View 中的某处:

from django import http

uidb64 = request.GET.get('uidb64')
token = request.GET.get('token')

if uidb64 is not None and token is not None:
from django.utils.http import urlsafe_base64_decode
uid = urlsafe_base64_decode(uidb64)
try:
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
user_model = get_user_model()
user = user_model.objects.get(pk=uid)
if default_token_generator.check_token(user, token) and user.is_active == 0:
# Do success stuff...
return http.HttpResponseRedirect(a_success_url)
except:
pass

return http.HttpResponseRedirect(a_failure_url)

关于python - 注册django后发送邮件确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292052/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com