Django-registration重新发送激活电子邮件与新代码

时间:2016-05-18 14:42:14

标签: python django python-2.7 django-registration

我正在使用django-registration具有唯一的电子邮件地址,并且我希望能够在用户请求并且帐户尚未处于活动状态时向电子邮件发送第二个激活表单。我在Stackoverflow上发现了这个link但是我不明白我应该把例程放在哪里。我把它放在我的应用程序的views.py中,我收到了错误

global name 'RegistrationProfile' is not defined

这是因为RegistrationProfile是注册中的模型,但是当发送激活表单时它不会在我的数据库中创建表/记录,所以我不明白我如何访问它。

欢迎任何建议。

1 个答案:

答案 0 :(得分:3)

好的,这就是我提出的解决方案。它可能不是最漂亮的,但它对我有用。

这已添加到views.py

from .forms import ResendActivationEmailForm
from django.core import signing
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string


def resend_activation_email(request):

    email_body_template = 'registration/activation_email.txt'
    email_subject_template = 'registration/activation_email_subject.txt'

    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."]

            REGISTRATION_SALT = getattr(settings, 'REGISTRATION_SALT', 'registration')
            for user in users:
                activation_key = signing.dumps(
                    obj=getattr(user, user.USERNAME_FIELD),
                    salt=REGISTRATION_SALT,
                    )
                context = {}
                context['activation_key'] = activation_key
                context['expiration_days'] = settings.ACCOUNT_ACTIVATION_DAYS
                context['site'] = get_current_site(request)

                subject = render_to_string(email_subject_template,
                                   context)
                # Force subject to a single line to avoid header-injection
                # issues.
                subject = ''.join(subject.splitlines())
                message = render_to_string(email_body_template,
                                           context)
                user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
                return render(request, 'registration/resend_activation_email_done.html')

    if not form:
        form = ResendActivationEmailForm()

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

这已添加到forms.py

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

我注册了一个名为resend_activation_email_form.html的新模板,该模板在重新发送电子邮件时使用,但我使用完全相同的模板发送电子邮件。

我之所以以电子邮件为基础是因为我使用过独特的电子邮件,但基于用户名可能更明智,因为django-registration定义为唯一。