如何使用 django-allauth 进行自定义注册?

Posted

技术标签:

【中文标题】如何使用 django-allauth 进行自定义注册?【英文标题】:How to do custom signup with django-allauth? 【发布时间】:2014-05-15 00:36:17 【问题描述】:

我正在尝试在注册时询问用户一些其他信息。我正在使用 django allauth 进行授权和身份验证。我尝试在注册过程中再添加三个字段。如果我运行它,它会显示标准表格和性别字段。但是,它似乎并没有真正起作用。如何保存数据?有人可以帮忙吗?提前谢谢!

已编辑:如果我只是使用

if form.is_valid():
    form.save()
    return redirect('/success/')

我得到一个错误:

save() missing 1 required positional argument: 'user'

我对 django 还是很陌生。

我在项目中创建了注册应用程序。

我把它放在 allauth_settings.py 中:

ACCOUNT_SIGNUP_FORM_CLASS = 'signups.forms.MySignupForm'

我的注册/model.py:

from django.contrib.auth.models import User
from django.db import models
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
import hashlib


class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    about_me = models.TextField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add= True, auto_now=False)
    updated = models.DateTimeField(auto_now_add= False, auto_now=True)

    GENDER_CHOICES = (
        ('m', 'Male'),
        ('f', 'Female'),
    )
    # gender can take only one of the GENDER_CHOICES options
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES,
                              verbose_name='Gender')

    def __unicode__(self):
        return self.user.username

    class Meta:
        db_table = 'user_profile'

    def profile_image_url(self):
        """
        Return the URL for the user's Facebook icon if the user is logged in via
        Facebook, otherwise return the user's Gravatar URL
        """
        fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook')

        if len(fb_uid):
            return "http://graph.facebook.com//picture?width=40&height=40".format(fb_uid[0].uid)

        return "http://www.gravatar.com/avatar/?s=40".format(hashlib.md5(self.user.email).hexdigest())

def account_verified(self):
    """
    If the user is logged in and has verified hisser email address, return True,
    otherwise return False
    """
    if self.user.is_authenticated:
        result = EmailAddress.objects.filter(email=self.user.email)

        if len(result):
            return result[0].verified

    return False


User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

我的signups/forms.py

from allauth.account.forms import SignupForm
from django import forms
from .models import UserProfile


class MySignupForm(SignupForm):
    class Meta:
        model = UserProfile

    gender = forms.CharField(max_length=1, label='gender')

    def save(self, user):
        user.gender = self.cleaned_data['gender']
        user.save()

我的signups/views.py

from django.template import RequestContext
from django.shortcuts import render_to_response
from .forms import SignupForm


def index(request):
    form = MySignupForm(request.POST or None)

    if form.is_valid:
        ???

    return render_to_response("signups/index.html", locals(),
                              context_instance=RequestContext(request))

我的index.html很基础,只是想看看表格的表示:

% extends 'account/base.html' %

% block head_title %ProjectName% endblock %

% block content %
    <form method="POST" action="">
         form.as_p 
        <input type="submit">
    </form>
% endblock %

【问题讨论】:

How to customize user profile when using django-allauth 的可能重复项 【参考方案1】:

您正在实例化SignupForm,这是标准形式,但不是您在视图中的MySignupForm。改成这样:

def index(request):
    form = MySignupForm()
    return render_to_response("signups/index.html", locals(),
                      context_instance=RequestContext(request))

【讨论】:

嗨桑托什,谢谢!我也设法找到了这个。我在上面编辑了他的代码。但是,即使我现在看到这些字段(带有性别),我也无法保存数据。如果我只使用 if form.is_valid(): form.save() return redirect('/success/') 我得到一个错误: save() missing 1 required positional argument: 'user'

以上是关于如何使用 django-allauth 进行自定义注册?的主要内容,如果未能解决你的问题,请参考以下文章

使用 django-allauth 时如何自定义用户配置文件

使用 django-allauth 启用 oauth 登录,但使用自定义提供程序

使用 django-allauth 额外数据添加自定义用户

自定义 django-allauth 登录视图

覆盖 django-allauth 的默认模板

使用 django-allauth 实现 Ajax 请求/响应