Django-등록 및 메일 확인 기능

11926 단어 Django
하나, 세팅에서.py에 메일 설정 추가
+
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'zhang1991'
DEFAULT_FROM_EMAIL = 'laowu <[email protected]'

2. 메일 발송 모듈(project/email.py)
from __future__ import unicode_literals
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import render


def send_activate_mail(request,to, subject, template, **kwargs):
    html = render(request, template+'.html',{'token':kwargs['token'],'username':kwargs['username']})
    text = render(request, template+'.txt', {'token':kwargs['token'],'username':kwargs['username']})

    msg = EmailMultiAlternatives(subject, text.content.decode('utf-8'), '[email protected]', ['[email protected]'])
    msg.attach_alternative(html.content.decode('utf-8'), "text/html")

    msg.send()

모형
from django.conf import settings
from django.db import models
# django    
from django.contrib.auth.hashers import make_password

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired
from itsdangerous import BadSignature,SignatureExpired

# Create your models here.

class Users(models.Model):
    nickname = models.CharField(max_length=16, null=False, blank=False, unique=True)
    email = models.EmailField(max_length=32, null=False, blank=False, unique=True)
    password = models.CharField(max_length=64, null=False, blank=False)
    head = models.ImageField(default="decault.png")
    age = models.CharField(max_length=3,blank=True,null=True)
    sex = models.CharField(max_length=2, blank=True, null=True)
    isactivate = models.BooleanField(default=False)

    def save(self):
        if not self.password.startswith('pbkdf2_'):
            self.password = make_password(self.password)
        super().save()

    #  token
    def generate_activate_token(self, expires_in=360):
        s = Serializer(settings.SECRET_KEY, expires_in)
        return s.dumps({'id': self.id})

    #token  
    @staticmethod
    def check_activate_token(token):
        s = Serializer(settings.SECRET_KEY)
        try:
            data = s.loads(token)
        except BadSignature:
            return '      '
        except SignatureExpired:
            return '      '
        user = Users.objects.filter(id=data.get('id'))[0]
        if not user:
            return '        '
        if not user.isactivate:
            user.isactivate = True
            user.save()
        return '    '

4. 보기 함수
from django.shortcuts import render,HttpResponse
from django.views.generic import ListView
from django.contrib import messages

from user.forms import  RegisterForm
from user.models import Users

# Create your views here.
from v2ex.email import send_activate_mail


def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            u = Users()
            u.nickname = form.cleaned_data['nickname']
            u.email = form.cleaned_data['email']
            u.password = form.cleaned_data['password']
            u.age = form.cleaned_data['age']
            u.sex = ' ' if form.cleaned_data['sex']==0 else ' '
            u.save()

            token = u.generate_activate_token().decode('utf-8')
            send_activate_mail(request, u.email, '    ', 'activate', token=token, username=u.nickname)

            messages.add_message(request, messages.INFO,  '      ,         !')
            return render(request,'user_info.html',context={'user':u})
        else:
            return render(request, 'register.html',context={'form':form,'errors': form.errors})
    else:
        form = RegisterForm()
    return render(request,'register.html',context={'form':form})


def login(request):
    return render(request,'login.html')


def user_info(request):
    return render(request,'user_info.html')

class UsersList(ListView):
    model = Users


def activate(request):
    token = request.GET['token']
    result = Users.check_activate_token(token)
    return HttpResponse(result)

5.urls 설정,user/urls.py
from django.urls import path
from . import views
app_name = 'user'

urlpatterns = [
    path(r'register/',views.register,name='register'),
    path(r'login/',views.login,name='login'),
    path(r'info/',views.user_info,name='info'),
    path(r'activate/',views.activate,name='activate')
]

6. 메일 템플릿(templates/email.html)
  • email.html
  • 
    "en">
    
        "UTF-8">
            
    
    
    

    Hello {{ username }}

    "http://127.0.0.1:8000/user/activate/?token={{token}}}"> 활성화

  • email.txt
  • "http://127.0.0.1:8000/user/activate/?token={{token}} "> 활성화

    좋은 웹페이지 즐겨찾기