我遇到了一些麻烦,关于如何实现我正在工作的场景。我是新的网络开发,所以请原谅我的天真。
我使用的是默认的Django管理员面板,我用自己创建的超级管理员登录。这个应用没有注册界面,所以只有管理员可以创建新用户。普通用户会收到一封包含他们凭据的电子邮件。这样他们就可以通过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")
我如何去实现的逻辑,管理员创建一个用户从管理面板和用户接收凭据登录。我也有一个SignUpView
下面的情况下,我是需要的。
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)
提前感谢!
1条答案
按热度按时间yhuiod9q1#
您可以在创建帐户时使用send_email函数创建发送电子邮件的管理操作。
管理操作-https://docs.djangoproject.com/en/3.2/ref/contrib/admin/actions/
发送电子邮件-https://docs.djangoproject.com/en/4.1/topics/email/