Home > OS >  Is there a way in Django where the superadmin can create normal users and the users gets an email wi
Is there a way in Django where the superadmin can create normal users and the users gets an email wi

Time:11-28

I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety.
I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users will them receive an email with their credential. So that they can login with through the LoginAPIView.

views.py

class LoginView(APIView):
    serializer_class = LoginSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

serializers.py

class LoginSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(max_length=255)
    password = serializers.CharField(min_length=8, write_only=True)


    class Meta:
        model = User
        fields = ["email", "password"]

    def validate(self, attrs):
        email = attrs.get("email")
        password = attrs.get("password")
        user = auth.authenticate(username=email, password=password)

        if not user:
            raise AuthenticationFailed("Invalid credentials")

        if not user.is_active:
            raise AuthenticationFailed("Account is not active, please contain admin")

        return {"email": user.email}

models.py

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email or not password:
            raise ValueError("Users must have both email and password")

        email = self.normalize_email(email).lower()

        user = self.model(email=email, **kwargs)
        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, password, **extra_fields):
        if not password:
            raise ValueError("Password is required")

        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user


class User(AbstractBaseUser, PermissionsMixin):
    # user data
    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

    # status
    is_active = models.BooleanField(default=True)
    is_verified = models.BooleanField(default=False)

    # timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["first_name", "last_name"]

    def __str__(self):
        return self.email

admin.py

from django.contrib import admin

from authentication.models import User


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ("email", "first_name","last_name")

How do I go about implementing the logic where the admin creates a user from the admin panel and the user receives the credentials to login. I also have a SignUpView below incase I it is needed.

views.py

class SignUpView(APIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user_data = serializer.data

        return Response(user_data, status=status.HTTP_201_CREATED)

Thanks in advance.!

CodePudding user response:

You can use create Admin actions that sends emails utilizing the send_email function when an account is created.

Admin Actions - https://docs.djangoproject.com/en/3.2/ref/contrib/admin/actions/

send_email - https://docs.djangoproject.com/en/4.1/topics/email/

  • Related