【问题标题】:Django: Add another field to django-registrationDjango:向 django-registration 添加另一个字段
【发布时间】:2014-05-25 22:51:56
【问题描述】:

我对 django 很陌生,我对 django-registration 非常迷茫。目前我已经设置了 django-registration,但我需要在其中添加另一个字段以获取电话号码。我需要注册字段中的电话号码字段,以便我可以使用 twilio 的 api 通过文本而不是电子邮件发送验证链接。我将如何将这一字段添加到 django-registration?

【问题讨论】:

  • 你能展示一下你已经拥有的吗?
  • 这是默认的 django-registration pastebin.com/dbTqd25d 这些是我的表单和models.py

标签: python django django-registration


【解决方案1】:

我在工作中与 django 一起工作,对于我们用来将模型附加到用户的那种问题,例如:

  • 您创建一个新模型,例如向用户提供 OneToOneField 的配置文件
  • 将所需字段添加到该配置文件模型,例如(tlf、国家、语言、日志...)
  • 在django admin中管理用户的同时创建admin.py来管理这个模型(profile)

配置文件模型示例

class Profile(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=255, blank=True, null=True, verbose_name='phone')
    description = models.TextField(blank=True, verbose_name='descripction')
    ...
    ...
    class Meta:
        ordering = ['user']
        verbose_name = 'user'
        verbose_name_plural = 'users'

admin.py 示例

# -*- coding: utf-8 -*-
from __future__ import unicode_literals    
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User


class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    filter_horizontal = ['filter fields']  # example: ['tlf', 'country',...]
    verbose_name_plural = 'profiles'
    fk_name = 'user'

class UserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active')

admin.site.unregister(User)  # Unregister user to add new inline ProfileInline
admin.site.register(User, UserAdmin)  # Register User with this inline profile

创建用户并将个人资料附加到他

# Create user
username = 'TestUser'
email = 'test@example.com'
passw = '1234'  
new_user = User.objects.create_user(username, email, passw)

# Create profile
phone = '654654654'
desc = 'Test user profile'
new_profile = Profile(user=new_user, phone = phone, description=desc)
new_profile.profile_role = new_u_prole
new_profile.user = new_user

# Save profile and user
new_profile.save()
new_user.save()

现在您将将此 Profile 模型附加到每个用户,并且您可以将您希望的字段添加到 Profile Model,例如,如果您:

user = User.objects.get(id=1)

您可以访问他的个人资料:

user.profile

并访问手机

user.profile.phone

【讨论】:

    【解决方案2】:

    不是 django-registration,但我自定义了一次 django-userena 以在注册表单中添加自定义字段。

    您可以查看代码here

    我确信该过程在 django-registration 中也大致相同:覆盖注册表单并添加自定义字段。

    但是,我相信 django-registration 不再维护。它是经典之作,效果很好,但也有其他选择。

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 1970-01-01
      • 2015-06-19
      • 2011-04-14
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多