Django开发笔记一

Django开发笔记二

Django开发笔记三

Django开发笔记四

Django开发笔记五

Django开发笔记六

1、邮箱激活

users app下,models.py:

class EmailVerifyRecord(models.Model):
code = models.CharField(max_length=20, verbose_name=u"验证码")
email = models.EmailField(max_length=50, verbose_name=u"邮箱")
send_type = models.CharField(verbose_name=u"发送类型",
choices=(("register", u"注册"), ("forget", u"忘记密码"), ("update_email", u"修改邮箱")),
max_length=50)
send_time = models.DateTimeField(verbose_name=u"发送时间", default=datetime.now) class Meta:
verbose_name = u"邮箱验证码"
verbose_name_plural = verbose_name def __unicode__(self):
return '{0}({1})'.format(self.code, self.email)

在utils app下:email_send.py:

# coding=utf-8

from random import Random
from django.core.mail import send_mail from users.models import EmailVerifyRecord
from touchrnb.settings import EMAIL_FROM def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str += chars[random.randint(0, length)]
return str def send_register_email(email, send_type="register"):
email_record = EmailVerifyRecord()
if send_type == "update_email":
code = random_str(4)
else:
code = random_str(16)
email_record.code = code
email_record.email = email
email_record.send_type = send_type
email_record.save() email_title = ""
email_body = "" if send_type == "register":
email_title = "慕学网激活链接"
email_body = " 请点击下面的链接激活你的帐号:http://127.0.0.1:8000/active/{0}".format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
if send_status:
pass elif send_type == "forget":
email_title = "慕学网密码重置链接"
email_body = " 请点击下面的链接重置密码:http://127.0.0.1:8000/reset/{0}".format(code) elif send_type == "update_email":
email_title = "慕学网在线邮箱修改验证码"
email_body = " 你的邮箱验证码为:{0}".format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
if send_status:
pass

settings.py:

EMAIL_HOST = "smtp.163.com"
EMAIL_PORT = 25
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = "xxxxxx"
EMAIL_USER_TLS = False
EMAIL_FROM = "[email protected]"

2、处理邮箱中的链接:

users.py:

url(r'^active/(?P<active_code>\w+)/$', ActiveUserView.as_view(), name="ActiveUserView"),

views.py:

class ActiveUserView(View):
def get(self, request, active_code):
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
user = UserProfile.objects.get(email=email)
user.is_active = True
user.save()
else:
return render(request, "active_fail.html") return render(request, "login.html")
04-04 12:38