在我的 Django 应用程序中完成注册后,我会发送电子邮件确认。出于安全原因,我需要找出如何在不在用户模型中添加新代码字段的情况下验证我在 url 中发送的代码。到目前为止,我在 url 和经过验证但未验证代码的用户名中发送随机代码。
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))
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/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决
作为新的阿里云用户,您可以50免费试用多种优惠,价值高达1,700美元(或8,500美元)。这将让您了解和体验阿里云平台上提供的一系列产品和服务。如果您以个人身份注册免费试用,您将获得价值1,700美元的优惠。但是,如果您是注册公司,您可以选择企业免费试用,提交基本信息通过企业实名注册验证,即可开始价值$8,500的免费试用!本教程介绍了如何设置您的帐户并使用您的免费试用版。关于免费试用在我们开始此试用之前,您还必须遵守以下条款和条件才能访问您的免费试用:只有在一年内创建的账户才有资格获得阿里云免费试用。通过此免费试用优惠,用户可以免费试用免费试用活动页面上列出的每种产品一次。如果您有多个帐
2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p
ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem
是否可以在PyYAML或Ruby的Psych引擎中禁用创建anchor和引用(并有效地显式列出冗余数据)?也许我在网上搜索时遗漏了一些东西,但在Psych中似乎没有太多可用的选项,而且我也无法确定PyYAML是否允许这样做.基本原理是我必须序列化一些数据并将其以可读的形式传递给一个不是真正的技术同事进行手动验证。有些数据是多余的,但我需要以最明确的方式列出它们以提高可读性(anchor和引用是提高效率的好概念,但不是人类可读性)。Ruby和Python是我选择的工具,但如果有其他一些相当简单的方法来“展开”YAML文档,它可能就可以了。 最佳答案