【问题标题】:Custom User's and implementations with forms自定义用户和表单实现
【发布时间】:2015-11-03 22:41:58
【问题描述】:

我在使用 django-registration-redux 时遇到问题。

我想向用户添加其他字段,如生日、电话等,但我很难在模型中扩展用户类。将这些字段添加到我的用户并在表单注册和登录中显示的最佳表单是什么?

【问题讨论】:

  • 我会考虑更改标题,因为它看起来与问题的实际正文无关
  • 谢谢,我觉得这个标题现在更适合身体了。

标签: python django


【解决方案1】:

我建议按照以下步骤操作:

  1. 定义您的用户模型,添加您想要的字段,例如birth_datephoto:

    # filename: myapp/models.py
    
    from django.db import models
    from django.utils.translation import ugettext as _
    from datetime import datetime
    from django.conf import settings
    from django.contrib.auth.models import AbstractUser, Group
    
    class MyUser(AbstractUser):
    
        birth_date = models.DateField(null=True)
        photo = models.ImageField(upload_to=..., null=True, blank=True, verbose_name=_("photo"))
    
  2. 创建自定义注册表单:

    # in file myapp/forms.py
    from django import forms
    from registration.forms import RegistrationForm
    
    class MyRegistrationForm(RegistrationForm):
    
        birth_date = ...
        photo = ...
    
  3. 编写自定义注册视图:

    # in file myapp/views.py
    
    from registration.backends.simple.views import RegistrationView
    from .forms import MyRegistrationForm
    
    class MyRegistrationView(RegistrationView):
    
        form_class = MyRegistrationForm
    
        def register(self, request, form):
    
            user = super(MyRegistrationView, self).register(request, form)
            user.birth_date = form.cleaned_data["birth_date"]
            user.photo = form.cleaned_data["photo"]
    
            user.save()
    
            return user
    
  4. 告诉系统你将使用你的自定义用户模型

    # in file settings.py
    AUTH_USER_MODEL = "myapp.MyUser"
    
  5. 添加一个 URL 以调用您的自定义注册视图

    # in file urls.py
    
    from myapp.views import MyRegistrationView
    ...
    
    urlpatterns = [
        ...
        url(r'^accounts/register/$', MyRegistrationView.as_view(), name="registration_register"),
        ...
    ]
    

【讨论】:

  • 我试过了,但在 models.py 中我得到了:错误:Loguear.MyUser.groups: (fields.E304) 'MyUser.groups' 的反向访问器与 'User.groups' 的反向访问器冲突.提示:在“MyUser.groups”或“User.groups”的定义中添加或更改related_name 参数。 Loguear.MyUser.user_permissions:(fields.E304)“MyUser.user_permissions”的反向访问器与“User.user_permissions”的反向访问器冲突。系统检查确定了 4 个问题(0 个已静音)。会有什么问题? (也出现了其他类似的错误)
  • 您似乎忘记在您的settings.py 中设置AUTH_USER_MODEL,或者您在未加载的设置文件中进行了设置。见:stackoverflow.com/questions/26703323/django-abstract-user-error
  • 感谢您的回复。我正在阅读此内容,发现 AUTH_USER_MODEL 已被弃用...对我的项目有什么影响?
  • 你能指出你在哪里读到的吗?这对我来说是新的。顺便说一句,你让它工作了吗?
  • 对此我很抱歉...我对 auth_profile_module 感到困惑,AUTH_USER_MODEL 可用...但是它不起作用。当我尝试进行迁移时,它显示“您正在尝试在没有默认值的情况下向 customuser 添加不可为空的字段‘密码’”。 (customuser 是我的模型)
猜你喜欢
  • 1970-01-01
  • 2019-05-19
  • 2019-03-22
  • 2011-12-26
  • 2014-02-04
  • 1970-01-01
  • 2020-12-14
  • 2016-06-20
  • 1970-01-01
相关资源
最近更新 更多