简体   繁体   English

Django注册 - 一些激活

[英]Django-registration - some activation

How can I force resending activation e-mail to user? 如何强制向用户重新发送激活电子邮件? Eg when he accidentaly deletes the mail, he clicks in link in my website, and django will send him new activation e-mail. 例如,当他意外删除邮件时,他点击我网站上的链接,django将向他发送新的激活电子邮件。

There's an admin action for doing that. 这样做有一个管理员操作 From the django-registration docs : 来自django-registration docs

How do I re-send an activation email? 如何重新发送激活邮件?

Assuming you're using the default backend, a custom admin action is provided for this; 假设您使用默认后端,则为此提供自定义管理操作; in the admin for the RegistrationProfile model, simply click the checkbox for the user(s) you'd like to re-send the email for, then select the “Re-send activation emails” action. 在RegistrationProfile模型的管理员中,只需单击您要为其重新发送电子邮件的用户的复选框,然后选择“重新发送激活电子邮件”操作。

There's no built-in automatic way of doing this (how should django-registration figure out that a random visitor is that guy who filled out the registration form 3 days ago and deleted his activation mail?). 没有内置的自动方式(django-registration应该如何确定随机访问者是3天前填写注册表并删除了他的激活邮件的人?)。

The following view function will render a form with single email field, then check if there are any users with this email not activated yet, recreate activation code if expired (hashing stuff was copypasted from RegistrationProfile) and finally send activation email. 以下视图函数将呈现具有单个电子邮件字段的表单,然后检查是否有任何用户尚未激活此电子邮件,如果已过期则重新创建激活码(散列内容是从RegistrationProfile复制的)并最终发送激活电子邮件。

class ResendActivationEmailForm(forms.Form):
    email = EmailField(required=True)

def resend_activation_email(request):
    context = Context()

    form = None
    if request.method == 'POST':
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = User.objects.filter(email=email, is_active=0)

            if not users.count():
                form._errors["email"] = (_("Account for email address is not registered or already activated."),)

            for user in users:
                for profile in RegistrationProfile.objects.filter(user=user):
                    if profile.activation_key_expired():
                        salt = sha_constructor(str(random())).hexdigest()[:5]
                        profile.activation_key = sha_constructor(salt+user.username).hexdigest()
                        user.date_joined = datetime.now()
                        user.save()
                        profile.save()

                    if Site._meta.installed:
                        site = Site.objects.get_current()
                    else:
                        site = RequestSite(request)

                    profile.send_activation_email(site)

                    context.update({"form" : form})
                    return render_to_response("registration/resend_activation_email_done.html", context)

    if not form:
        form = ResendActivationEmailForm()

    context.update({"form" : form})
    return render_to_response("registration/resend_activation_email_form.html", context)

I updated the ilya b. 我更新了ilya b。 method resend_activation_email. 方法resend_activation_email。 The old method show error of sha deprecation in python >= 2.5 旧方法在python> = 2.5中显示sha弃用的错误

def resend_activation_email(request):

    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')

    context = Context()

    form = None
    if request.method == 'POST':
        form = ResendActivationEmailForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            users = User.objects.filter(email=email, is_active=0)

            if not users.count():
                form._errors["email"] = ("Account for email address is not registered or already activated.")

            for user in users:
                for profile in RegistrationProfile.objects.filter(user=user):
                    if profile.activation_key_expired():
                        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                        profile.activation_key = hashlib.sha1(salt+user.email).hexdigest()
                        user.date_joined = datetime.datetime.now()
                        user.save()
                        profile.save()

                    if Site._meta.installed:
                        site = Site.objects.get_current()
                    else:
                        site = RequestSite(request)

                    profile.send_activation_email(site)

                    context.update({"form" : form})
                    return render(request, 'registration/resend_activation_email_done.html', context)

    if not form:
        form = ResendActivationEmailForm()

    context.update({"form" : form})
    return render(request, 'registration/resend_activation_email_form.html', context)

My (ugly) solution was to create my own login view: 我(丑陋)的解决方案是创建我自己的登录视图:

from django.contrib.auth.views import login as django_login

def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          redirect_authenticated=None,
          authentication_form=AuthenticationForm):
    """
        Redirect to redirect_authenticated if user is authenticated or
        delegate to contrib login otherwise.
    """

    form = authentication_form(data=request.POST)

    if request.method == "POST":
        if not form.is_valid():

            non_field_errors = form.non_field_errors()

            if non_field_errors:
                # test if the account is not active
                user_inactive = non_field_errors[0].find(_("This account is inactive.")) != -1

                if user_inactive:
                    return render_to_response(template_name, {
                        'form': form,
                        'user_inactive' : user_inactive,
                    }, context_instance=RequestContext(request))

    return django_login(request, template_name=template_name,
              redirect_field_name=redirect_field_name,
              authentication_form=authentication_form)

And then use the context variable in template: 然后在模板中使用上下文变量:

{% if user_inactive %}  
  <a href="/activation/resend/">Resend activation link</a>
{% else %}   
  <a href="{% url django.contrib.auth.views.password_reset %}">Forgot your password?</a> 
{% endif %}

When the user clicks on the resend activation link, a form asking for the registered email appears. 当用户点击重发激活链接时,会出现一个要求注册电子邮件的表单。 Submiting the form triggers a new account activation email. 提交表单会触发新的帐户激活电子邮件。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM