Django用户通过电子邮件进行注册和身份验证

4
我想通过发送 激活邮件 来激活用户。我猜在 Django 1.6 中当前没有这个功能。Django 编写的 user-registration 应用程序似乎可以实现此目的。但是,我对它在 forms.py 中提供的 DefaultForm 有一些疑问。我想在其中包含更多字段,该怎么办?如果我安装了这个应用程序,是否直接更改代码以添加更多字段是一个好主意?还有没有更好的方法来实现同样的功能。
views.py中,我看到一些方法没有被实现。我不清楚这些方法需要做什么。我应该将URL重定向到这里的页面吗?
def register(self, request, **cleaned_data):
 raise NotImplementedError

def activate(self, request, *args, **kwargs):

        raise NotImplementedError

    def get_success_url(self, request, user):
        raise NotImplementedError
3个回答

8

您需要先让他们注册,并将其标记为is_active=False,暂时这样做。可以像这样:

from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.http import HttpResponseRedirect

def signup(request):
  # form to sign up is valid
  user = User.objects.create_user('username', 'email', 'password')
  user.is_active=False
  user.save()

  # now send them an email with a link in order to activate their user account
  #   you can also use an html django email template to send the email instead
  #   if you want
  send_mail('subject', 'msg [include activation link to View here to activate account]', 'from_email', ['to_email'], fail_silently=False)

 return HttpResponseRedirect('register_success_view')

当用户点击电子邮件中的链接后,它会将他们带到下一个页面(注:您需要在电子邮件中放置链接以便知道是哪个用户。这可能是16位数字盐或其他内容。下面的视图使用了 user.pk ):

def activate_view(request, pk):
  user = User.objects.get(pk=pk)
  user.is_active=True
  user.save()
  return HttpResponseRedirect('activation_success_view')

希望这能帮到你。祝你好运!

激活链接会是什么样子?如何区分不同的注册链接?谢谢。 - Alston

2
基本上,您可以使用Django的用户模型(https://docs.djangoproject.com/en/1.9/ref/contrib/auth/)。但是,在用户模型中,电子邮件不是必填字段。您需要修改模型以使电子邮件成为必填字段。
在您的视图中,您可能需要以下方法:
1)注册:注册后,设置user.is_active=False并调用函数send_email将激活链接包含在电子邮件中。在链接中,您可能希望包含用户的信息(例如,user.id),因此当用户单击链接时,您知道要激活哪个用户。
2)send_email:向用户的电子邮件地址发送验证链接。该链接包括用户的id。例如:http://127.0.0.1:8000/activation/?id=4 3)激活:从URL中获取id信息,使用id=request.GET.get('id')。查询id为id的用户=user。设置user.is_active=True。
实际上,我已经实现了一个可重用的应用程序,就像您的请求一样。如果您有兴趣,请查看此链接(https://github.com/JunyiJ/django-register-activate)。
希望这可以帮到您。祝你好运!

0

看看这个...我希望它不仅能帮助你解决问题,还能解释清楚。因为我认为django-registration应用程序是为默认的Django用户而设计的。所以,如果你想在注册表单中添加额外的字段,开始考虑自定义你的Django用户和其身份验证。你不需要django-registration应用程序在这里。以下是一些教程,可以帮助你。

http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/

等等还有更多...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接