django-allauth: How to set user to active only after e-mail verification

前端 未结 3 1340
谎友^
谎友^ 2021-02-06 13:12

I\'m using django-allauth primarily as a way to create user accounts for the admin backend. What I would like to have happen is:

1) When a user goes through the sign up

相关标签:
3条回答
  • 2021-02-06 13:50

    ACCOUNT_EMAIL_VERIFICATION (=”optional”) Determines the e-mail verification method during signup – choose one of “mandatory”, “optional”, or “none”. When set to “mandatory” the user is blocked from logging in until the email address is verified. Choose “optional” or “none” to allow logins with an unverified e-mail address. In case of “optional”, the e-mail verification mail is still sent, whereas in case of “none” no e-mail verification mails are sent.

    0 讨论(0)
  • 2021-02-06 13:53

    I seemed to have (mostly) resolved my issue by using signals. This post gave me the idea (but unfortunately didn't provide any code examples), while this site gave me some actual concrete examples to modify (something I've found to be a rare commodity in the Django world).

    I ended up putting the following code in my page's view.py file -- I know models.py is recommended for signals, but the models being used in question are actually from the allauth package:

    from allauth.account.signals import user_signed_up, email_confirmed
    from django.dispatch import receiver
    from django.contrib.auth.models import Group
    from django.contrib.auth.models import User
    from allauth.account.models import EmailAddress
    
    @receiver(user_signed_up)
    def user_signed_up_(request, user, **kwargs):
    
        user.is_active = False
        user.is_staff = True
        Group.objects.get(name='SurveyManager').user_set.add(user)
    
        user.save()
    
    @receiver(email_confirmed)
    def email_confirmed_(request, email_address, **kwargs):
    
        new_email_address = EmailAddress.objects.get(email=email_address)
        user = User.objects.get(new_email_address.user)
        user.is_active = True
    
        user.save()
    

    The only thing that isn't quite working yet is the email_confirmed signal processing -- it's claiming "EmailAddress matching query does not exist", when it clearly does match in the database entries, but I'll go ahead and post that in a separate question.

    0 讨论(0)
  • 2021-02-06 14:06

    I know this is an old post but I came across this thread in my own searches. In reply to your email_confirmed problem, use email=kwargs['email_address'].email in your EmailAddress instance call.

    @receiver(email_confirmed)
    def email_confirmed_(request, *args, **kwargs):
        user = request.user
        new_email_address = EmailAddress.objects.get(
            email=kwargs['email_address'].email)
        user = User.objects.get(
            email=new_email_address.user)
        user.is_active = True
        user.save()
    
    0 讨论(0)
提交回复
热议问题