如何在rest框架中为我的注册视图编写登录视图?
Posted
技术标签:
【中文标题】如何在rest框架中为我的注册视图编写登录视图?【英文标题】:How to write a login view for my register view in rest frame work? 【发布时间】:2022-01-12 05:56:24 【问题描述】:我是 Django 和其余框架的初学者,我正在尝试使用其余框架为我的注册视图编写一个基于类的登录视图,请帮助我编写一个基于类的登录视图,重要的是视图是基于类的休息 这是我的项目的注册视图,然后是其底部的序列化程序
class RegisterView(GenericAPIView):
serializer_class = UserSerializer
permission_classes = (permissions.AllowAny,)
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
print(current_site)
# relativeLink = reverse('verify-email')
# print(type(relativeLink))
absurl = 'http://' + current_site + "?token=" + str(token)
email_body = 'سلام' + user.username + '\nبرای فعال سازی حساب خود وارد لینک زیر شوید' + '\n' \
+ absurl
data = 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email'
Util.send_email(data)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
它是serializer.py中的一个寄存器视图序列化器
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=65, min_length=8, write_only=True)
confirm_password = serializers.CharField(
max_length=65, min_length=8, write_only=True)
def validate_email(self, value):
lower_email = value.lower()
if User.objects.filter(email__iexact=lower_email).exists():
raise serializers.ValidationError("ایمیل تکراری است")
return lower_email
def validate(self, data):
if not data.get('password') or not data.get('confirm_password'):
raise serializers.ValidationError("لطفا پسورد را وارد و تایید کنید ")
if data.get('password') != data.get('confirm_password'):
raise serializers.ValidationError("پسورد اشتباه است")
return data
class Meta:
model = User
fields = ['username', 'email', 'password', 'confirm_password'
]
write_only_fields = ('password', 'repeat_password')
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.set_password(validated_data['confirm_password'])
user.save()
return user
【问题讨论】:
【参考方案1】:class LoginView(APIView):
def post(self, request):
username = request.data['username']
password = request.data['password']
# use a method to get access token (from the package you are using)
# access token class will return access token if the user is authenticated
# otherwise it will return error response
pass
【讨论】:
以上是关于如何在rest框架中为我的注册视图编写登录视图?的主要内容,如果未能解决你的问题,请参考以下文章