python - 自定义用户和表单的实现

标签 python django

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

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

最佳答案

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

  1. 定义您的用户模型,添加您想要的字段,例如出生日期照片:

    # 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. 编写自定义注册 View :

    # 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 来调用您的自定义注册 View

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

关于python - 自定义用户和表单的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510474/

相关文章:

python - 如何将 lazy_gettext 与 Pylons 和 setup.py 一起使用

python - 什么是 O(n) 算法将两个等长列表按顺序配对?

Django 和 PostgreSQL 全文搜索 : Some terms not found by search lookup

python - 测试 niceness 是否被正确应用

python - 如何将字典从路由函数传递到另一个函数?

css - 我似乎无法使用 Django 加载我的静态文件

python - 将日期时间从 Objective C 传递到 Django

python - "NodeAlreadySaved "使用djangocms发布页面更改时报错

django - 如何在aws elasticbean上安装redis和celery

python - 发生错误时如何从 Django shell 获取返回值 !=0