【问题标题】:How Can I add Choices in the Django User model如何在 Django 用户模型中添加选项
【发布时间】:2021-10-26 08:34:54
【问题描述】:

我想向 Django 用户模型添加两个选项,并且我想从 UserCreationForm 继承一个从 django.contrib.auth.forms 派生的表单。当我使用下面的代码时,我得到了不同的错误。谁能提出解决方案为此?

forms.py

TYPE_CHOICES =(
("individual", "Individual"),
("company", "Company"),
)


class UserForm(UserCreationForm):
    first_name = forms.CharField(max_length=50)
    type = forms.ChoiceField(choices=TYPE_CHOICES)

    class Meta:
        model = User
        fields = ['first_name','type']

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

TYPE_CHOICES =(
    ("individual", "Individual"),
    ("company", "Company"),
)

class User(AbstractUser):
    type = models.CharField(choices=TYPE_CHOICES,max_length=20)

【问题讨论】:

    标签: django-users python-3.9


    【解决方案1】:

    您可以为此使用 django 模型的 choices。首先为您的选择创建对象。

    your_choices = (
        (1, u'Active'),
        (2, u'Inactive')
    )
    

    将这些选项添加到您的模型类中。

    choice_field = models.IntegerField(choices=your_choices)
    

    现在扩展您的表单类。

    class RegistrationForm(UserCreationForm):
            first_name = forms.CharField(max_length=30)
            last_name = forms.CharField(max_length=30)
            email = forms.EmailField(max_length=75)
            choice_field = forms.ChoiceField(choices=your_choices)
        
            class Meta:
                model = User
                fields = ("first_name", "last_name", "email", "choice_field",)
    

    【讨论】:

    • 这里我使用了 Django 用户模型。当我在 'class User(AbstractUser):' 中使用 'choice_field = models.IntegerField(choices=your_choices)' 时出现错误。你能展示如何在models.py文件中编写代码。@vivekpadia70
    • 你可以跟着这个教程raturi.in/blog/how-extend-django-user-model
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多