python-Django自定义注册字段

对于在django-registration注册表单/流程中添加自定义字段的看似简单的问题,我对提供的答案范围越来越困惑.这应该是该软件包的默认的,已记录的方面(不要忘了,因为它是这样一个功能齐全的软件包),但是解决该问题的方法令人眼花.乱.

谁能给我最简单的解决方案,以使UserProfile模型数据包含在默认注册注册页面中?

更新:

我最终使用了Django Registration自己的信号来给我这个漏洞修复程序.这是特别丑陋的,因为我不得不对布尔值使用POST属性进行尝试,因为我发现如果将其保留为空,则复选框不会返回任何内容.

希望对改进此方法或最佳实践有任何建议.

我的应用程式/ models.py

from registration.signals import user_registered
from django.dispatch import receiver

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    event_commitments = models.ManyToManyField(Event, null=True, blank=True)
    receive_email = models.BooleanField(default=True)

@receiver(user_registered)
def registration_active_receive_email(sender, user, request, **kwargs):
    user_id = user.userprofile.id
    user = UserProfile.objects.get(pk=user_id)

    try:
        if request.POST['receive_email']:
            pass
    except:
        user.receive_email = False
        user.save()

注册应用程序/forms.py

class RegistrationForm(forms.Form):

    # default fields here, followed by my custom field below

    receive_email = forms.BooleanField(initial=True, required=False)

谢谢

解决方法:

您所拥有的似乎是可行的方法.

我浏览了django-registration代码,并根据注册视图中的以下注释提出了另一种解决方案.我不确定这是否更干净,但是如果您不喜欢信号,那很好.如果您打算进行更多的自定义,这也提供了一条更容易的途径.

# from registration.views.register:
"""
...
2. The form to use for account registration will be obtained by
   calling the backend's ``get_form_class()`` method, passing the
   ``HttpRequest``. To override this, see the list of optional
   arguments for this view (below).

3. If valid, the form's ``cleaned_data`` will be passed (as
   keyword arguments, and along with the ``HttpRequest``) to the
   backend's ``register()`` method, which should return the new
   ``User`` object.
...
"""

您可以创建一个自定义后端并覆盖上述方法:

# extend the provided form to get those fields and the validation for free
class CustomRegistrationForm(registration.forms.RegistrationForm):
    receive_email = forms.BooleanField(initial=True, required=False)

# again, extend the default backend to get most of the functionality for free
class RegistrationBackend(registration.backends.default.DefaultBackend):

    # provide your custom form to the registration view
    def get_form_class(self, request):
        return CustomRegistrationForm

    # replace what you're doing in the signal handler here
    def register(self, request, **kwargs):
        new_user = super(RegistrationBackend, self).register(request, **kwargs)
        # do your profile stuff here
        # the form's cleaned_data is available as kwargs to this method
        profile = new_user.userprofile
        # use .get as a more concise alternative to try/except around [] access
        profile.receive_email = kwargs.get('receive_email', False)
        profile.save()
        return new_user

要使用自定义后端,则可以提供单独的URL.在包含默认URL之前,请写2个指向您自定义后端的conf. Urls按照定义的顺序进行测试,因此,如果在包含默认值之前定义了这两个值,则将在测试默认值之前捕获这两个值.

url(r'^accounts/activate/(?P<activation_key>\w+)/$',
    activate,
    {'backend': 'my.app.RegistrationBackend'},
    name='registration_activate'),
url(r'^accounts/register/$',
    register,
    {'backend': 'my.app.RegistrationBackend'},
    name='registration_register'),

url(r'^accounts/', include('registration.backends.default.urls')),

这些文档实际上描述了所有这些内容,但是它们并不是特别易于访问(没有readthedocs).它们都包含在项目中,而我正在浏览它们here.

上一篇:php – 在Woocommerce注册表单中添加条款和条件复选框


下一篇:php-如何将注册系统的错误回显到另一个索引文件