Django:单击电子邮件中的激活链接后如何自动登录用户?

时间:2018-08-07 20:59:46

标签: django django-templates django-views

我想在用户单击激活帐户链接后自动登录。

这是我的views.py

def signup(request):
    if request.user.is_authenticated:
        if request.user.is_active:
            return redirect('/')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            to_email = form.cleaned_data['email']
            email_suffix = to_email.split("@")[-1]
            university = University.objects.get(email_suffix=email_suffix)
            user.is_active = False
            user.university = university
            user.save()
            current_site = get_current_site(request)
            subject = 'Activate Your Account'
            html_content = render_to_string('core/email_templates/activate_account_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            text_content = strip_tags(html_content)
            email = EmailMultiAlternatives(subject, text_content, to=[to_email])
            email.attach_alternative(html_content, "text/html")
            email.send()
            message = ('<p class="bigTitle">Nearly Done...</p>'
                        '<p class="noMargin">We\'ve just sent you an activation'
                        ' email. Click the link in the email to activate your'
                        ' account.</p>')
            return render(request, 'core/signup.html', {'message': message })
    else:
        form = UserCreationForm(label_suffix="")
    return render(request, 'core/signup.html', {'form': form })

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = CustomUser.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('/')
    else:
        return HttpResponse('Activation link is invalid!')

这是我的基本模板的一部分,其中显示了相应的登录/注销链接:

<div id="menuWrapper">
  <div id="menu">
    <a class="menuItem" href="/?order=top" >Community</a>
    {% if user.is_authenticated %}
      <a href="{% url 'core:profile' user.username %}" class="menuItem">Profile</a>
      <a href="{% url 'logout' %}" class="menuItem">Log Out</a>
    {% else %}
      <a class="menuItem" href="{% url 'core:login' %}">Log In</a>
      <a class="menuItem" href="{% url 'core:signup' %}">Sign Up</a>
    {% endif %}
  </div>
</div>

看看activate中用于登录用户的代码,我本以为在将用户重定向到主页时,该用户将显示为登录状态,但是事实并非如此。登录/注销链接显示“登录”和“注册”。

如果任何人都可以告诉我该怎么做,以便激活链接自动将用户登录,我将不胜感激。

杰克

0 个答案:

没有答案