【问题标题】:How to send an authentication email in django?如何在 django 中发送身份验证电子邮件?
【发布时间】:2020-08-15 12:00:36
【问题描述】:

我如何使用 django 电子邮件框架,在用户注册后,我会向他发送一个特殊的链接来确认他的帐户。我知道有关于如何发送电子邮件的问题,但请帮助我进行身份验证。

【问题讨论】:

    标签: python django authentication


    【解决方案1】:

    Farhadur Reja Fahim 在帖子中解释了以下代码。要深入了解代码,请访问他的帖子Email COnfirmation

    settings.py

    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'youremail@gmail.com'
    EMAIL_HOST_PASSWORD = 'yourpassword'
    EMAIL_PORT = 587
    

    token.py

    from django.contrib.auth.tokens import PasswordResetTokenGenerator
    from django.utils import six
    class TokenGenerator(PasswordResetTokenGenerator):
        def _make_hash_value(self, user, timestamp):
            return (
                six.text_type(user.pk) + six.text_type(timestamp) +
                six.text_type(user.is_active)
            )
    account_activation_token = TokenGenerator()
    

    forms.py

    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth.models import User
    class SignupForm(UserCreationForm):
        email = forms.EmailField(max_length=200, help_text='Required')
        class Meta:
            model = User
            fields = ('username', 'email', 'password1', 'password2')
    

    views.py

    from django.http import HttpResponse
    from django.shortcuts import render, redirect
    from django.contrib.auth import login, authenticate
    from .forms import SignupForm
    from django.contrib.sites.shortcuts import get_current_site
    from django.utils.encoding import force_bytes, force_text
    from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
    from django.template.loader import render_to_string
    from .tokens import account_activation_token
    from django.contrib.auth.models import User
    from django.core.mail import EmailMessage
    def signup(request):
        if request.method == 'POST':
            form = SignupForm(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 = 'Activate your blog account.'
                message = render_to_string('acc_active_email.html', {
                    'user': user,
                    'domain': current_site.domain,
                    'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                    '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 HttpResponse('Please confirm your email address to complete the registration')
        else:
            form = SignupForm()
        return render(request, 'signup.html', {'form': form}
    
    def activate(request, uidb64, token):
        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
            user.save()
            login(request, user)
            # return redirect('home')
            return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
        else:
            return HttpResponse('Activation link is invalid!')
    

    acc_active_email.html

    {% autoescape off %}
    Hi {{ user.username }},
    Please click on the link to confirm your registration,
    http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
    {% endautoescape %}
    

    urls.py

    from django.conf.urls import url
    from . import views
    urlpatterns = [
        url(r'^$', views.home, name='home'),
        url(r'^signup/$', views.signup, name='signup'),
        url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
            views.activate, name='activate'),
    ]
    

    【讨论】:

    • django.utils.six 不再可用
    • 这是我想要的最后一件事,你一直很有帮助。帮我找到六个的替代品。
    • @Liel 你可以使用six 代替 from django.utils import 六。
    【解决方案2】:

    Forms.py

    from django.db.models import Q
    from django.core.exceptions import ObjectDoesNotExist
    from django.contrib.auth.models import User
    from django import forms
    from django.contrib.auth import authenticate
    
    class LoginForm(forms.Form):
        email = forms.CharField()
        password = forms.CharField(
            widget=forms.PasswordInput(render_value=False)
            )
    
        def clean(self):
            user = self.authenticate_via_email()
            if not user:
                raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
            else:
                self.user = user
            return self.cleaned_data
    
        def authenticate_user(self):
            return authenticate(
                username=self.user.username,
                password=self.cleaned_data['password'])
    
        def authenticate_via_email(self):
            """
                Authenticate user using email.
                Returns user object if authenticated else None
            """
            email = self.cleaned_data['email']
            if email:
                try:
                    user = User.objects.get(email__iexact=email)
                    if user.check_password(self.cleaned_data['password']):
                        return user
                except ObjectDoesNotExist:
                    pass
            return None
    

    Views.py

    def LoginRequest(request):
        form = LoginForm(request.POST or None)    
        if request.method == 'POST' and form.is_valid():
            user = form.authenticate_user()
            login(request, user)
            return HttpResponseRedirect(reverse('Hello'))
    
        return render(request, 'login.html',{'form': form})
    

    【讨论】:

    • 发送电子邮件怎么样(我没有使用用户名)并且是forms.py的第一个代码?
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 2018-08-07
    • 2013-11-03
    • 2021-10-18
    • 1970-01-01
    • 2011-12-08
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多