创建邀请对象时处理cookie

时间:2017-03-15 02:08:51

标签: python django django-forms django-1.9

我想实现直接向用户注册帐户的功能。将有一个请求邀请按钮。当用户点击带有电子邮件地址的请求邀请时,将使用令牌发送链接,当用户点击该链接时,用户将被重定向到注册页面。

class Invite(models.Model):
    # INVITE_CHOICES = (
    # ('G', 'General'),
    # ('I', 'Invitational'),
    # )
    user = models.OneToOneField(User)
    email = models.EmailField()
    cookie = models.UUIDField(default=uuid.uuid4)
    token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    timestamp = models.DateTimeField(auto_now_add=True)

class InviteForm(forms.ModelForm):
    email = forms.EmailField()
    class Meta:
        model = Invite
        fields = ['email']

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get('email')
        print('###############################')
        print ('email', email)
        email_qs = Invite.objects.filter(email__iexact=email)
        if not email:
            raise forms.validationError('Please! fill in your email address')
        if email_qs.exists():
            print ('sorry the email exists')
            raise forms.validationError('Sorry! This email already exists')
        return email

def invite_user(request):
    form = InviteForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
        # data for sending mail
        form_email = form.cleaned_data.get('email')
        # from_email = settings.EMAIL_HOST_USER
        user = User.objects.create_user(form.cleaned_data.get('email'))
        user.is_active = False
        user.save()
        invite, created = Invite.objects.get_or_create(user=user, email=email)
        if created:
            invite.token = get_token()
            invite.save()
        return HttpResponseRedirect('/')
    context = {"form": form}
    return render(request, "home.html", context)

0 个答案:

没有答案