简体   繁体   中英

Django Custom User Model add property

My model is relatively simple, but I want users to be member of a club. Superusers are not members of a club.

I decided to use a Custom User Model Extending AbstractBaseUser and created the models, managers and everything works fine. Now I want to extend the model by a property.

models.py:

from .managers import MyUserManager

class K2User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('active'), default=True)
 #   club_name = models.ForeignKey(Clubs, null=True, 

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def get_club_name(self):
        return self.club_name

    def __str__(self):
        return self.email

class Clubs(models.Model):
    club_name = models.CharField(max_length=32, unique=True)
    club_create_date = models.DateTimeField('date created')
    club_address = models.CharField(max_length=200)
    email = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, verbose_name=_('user'), on_delete=models.CASCADE)

managers.py

from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _

class MyUserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):

        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
       # club_name = club_name
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_staff', False)

        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_staff', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        return self._create_user(email, password, **extra_fields)

how can I add the club name to a normal user, so that he has to be member of a club, but the superuser does not have this property (or just set it null)?

** Edit **

in my admin view I still only see one member for each club - I guess I have to tinker with the admin.py for that?

admin.py:

class K2UserAdmin(UserAdmin):
    add_form = K2UserCreationForm
    form = K2UserChangeForm
    model = K2User
    list_display = ('email', 'date_joined', 'is_active',)# 'merchant',)
    list_filter = ('email', 'date_joined', 'is_active',)# 'merchant',)
    fieldsets = ( (None,            { 'fields': ('email', 'password') } ),
                  ('Permissions',   { 'fields': ('date_joined', 'is_active') } ), )
    add_fieldsets = ( (None,    {'classes': ('wide',),
                       'fields': ('email', 'password1', 'password2', 'date_joined', 'is_active') } ), )
    readonly_fields = ('date_joined',)    

admin.site.register(K2User, K2UserAdmin)
admin.site.register(Clubs)

The best way to implement this is as follows:

  1. First of all, you need to create one model between Club and User (rather than create M2M field). I named it Enrollment .
  2. Put Club and User foreign key this model.

So:

class Enrollment(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=_('enrollment_users'), on_delete=models.CASCADE)
   club = models.ForeignKey(Club, related_name=_('enrollment_clubs'), on_delete=models.CASCADE)

If you follow this way, you can do anything you want in this relation in the future.

Hope it help.

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