Python Django Authentication Users and Authorization Add to Group

K.D. Harris
K.D. Harris
10,828 Points

add new editor to "Editors" group.

I have looked over this several times and it still will not pass. I'm not sure what is wrong with this code.

accounts/models.py
from django.contrib.auth.models import (
    PermissionsMixin,
    BaseUserManager,
    AbstractBaseUser,
    Permission,
    Group
)
from django.db import models
from django.utils import timezone


class UserManager(BaseUserManager):
    def create_user(self, email, dob, accepted_tos=None, password=None):
        if not accepted_tos:
            raise ValueError("Users must accept the terms of service")

        user = self.model(
            email=self.normalize_email(email),
            dob=dob,
            accepted_tos=True
        )
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, dob, password):
        user = self.create_user(
            email,
            dob,
            accepted_tos=True,
            password=password
        )
        user.is_staff = True
        user.is_superuser = True
        user.save()
        return user

    def create_editor(self, email, dob, password):
        user = self.create_user(
            email,
            dob,
            accepted_tos=True,
            password=password
        )
        try:
            editors = Group.objects.get(name__iexact="Editors")
            user.groups.add(editors)
            user.save()
        except Group.DoesNotExist:
            editors = Group.objects.create(name="Editors")
            editors.permissions.add(Permission.objects.get(codename="can_give_discount"))
            user.groups.add(editors)
            user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    dob = models.DateField()
    accepted_tos = models.BooleanField()
    is_staff = models.BooleanField(default=False)
    joined_at = models.DateTimeField(default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["dob"]

1 Answer

Jordan Hoover
Jordan Hoover
Python Web Development Techdegree Graduate 48,601 Points

Hey! Not sure if you still need help, but you'll need to add the user and save them outside of the try/catch block.

K.D. Harris
K.D. Harris
10,828 Points

thank you, that solution worked! :)