简体   繁体   中英

Django AbstractBaseUser MultipleChoiceField

I have created a custom user model with AbstractBaseUser like this:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    preference = models.CharField(max_length=400)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'preference']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

For the preference field i don't want a char field, but to create a MultipleChoiceField and when a user sign up to choose what he/she wants from the choices. Is there a simple way to do this? I have a similar form which i used for different purpose:

class CategoryForm(forms.Form):
    def __init__(self, *args, **kwargs):
        categories = kwargs.pop("Category")
        super(CategoryForm, self).__init__(*args, **kwargs)
        self.fields["Category"] = forms.MultipleChoiceField(choices=categories, label='Click this to select categories')

EDIT

class CustomUser(AbstractBaseUser, PermissionsMixin):
    category_list = pickle.load(open("/home/anonymous/Documents/Diploma-Recommender/Recommendation/Dataset"
                                     "/category_list.pickle", "rb"))
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    category_tuple = ((),)
    for j in category_list:
        category_tuple = category_tuple + ((j, j),)
    category_tuple = list(category_tuple)
    category_tuple.pop(0)
    category_tuple = tuple(category_tuple)
    preference = ArrayField(
        models.CharField(choices=category_tuple, null=True, max_length=50, blank=True, default=None),
    )

    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'preference']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

if your multiple choice is sth like active diactive you can just specify those like this:

CHOICES = (('one','one'), ('two','two') ...)
preference = models.CharField(max_length=400, choices = CHOICES)

this works if you want to get the gender or some limited choices, but if your choices is from different model like category and there is a model Category if the number of choices is 1 ForeignKey and if it is more than 1 use ManyToMany relation in your User model

and if you use ModelForm django handles it for you.

I would recommend using an ArrayField in your model if you are using postgreSQL (which you should be.). This will accomplish your goal of multiple choices in a model field.

from django.contrib.postgres.fields import ArrayField

class CustomUser(AbstractBaseUser, PermissionsMixin):
    CATEGORY_1 = 'Category_1'
    CATEGORY_2 = 'Category_2'
    CATEGORY_3 = 'Category_3'

    CATEGORY_TYPE_CHOICES = [
        (CATEGORY_1, 'Category_1'),
        (CATEGORY_2, 'Category_2'),
        (CATEGORY_3, 'Category_3')
    ]

     category = ArrayField(
        max_length=10,
        choices=CATEGORY_TYPE_CHOICES,
        null=True,
        default=None,
        blank=True
    )

Read more here: Django Model MultipleChoice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM