def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: raise ValidationError(serializer.errors)
def test_update_user(self): data = UserSerializer(self.user).data data.update({ "username": "******", }) response = self.client.put(reverse('DetailUser', args=[self.user.id]), data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): new_user = serializer.save() return Response(serializer.date, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): user = get_object_or_404(User, pk = pk) serializer = UserSerializer(instance=user, data=request.date) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else : return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format='json'): #serialize the data sent from the front end serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() #after the user is saved, create a token for the user if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ConsumerTimeSlotMappingRelationSerializer(serializers.ModelSerializer): consumer = UserSerializer() time_slot = ProvidersTimeSlotSerializer() class Meta: model = ConsumerTimeSlotMapping fields = "__all__"
def post(self, request): user = User.objects.create_user(email=request.data['email'], password=request.data['password']) #user.set_password(request.data['password']) #user.save() serializer = UserSerializer(user) return Response(serializer.data)
class PostSerializer(HyperlinkedModelSerializer): author = UserSerializer() class Meta: model = Post fields = ('id', 'front_image_url', 'title', 'text', 'author', 'created_at', 'updated_at')
class NotesSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Notes fields = '__all__'
class LocationConnectionsSerializer(serializers.ModelSerializer): connections = ConnectionListSerializer(many=True, read_only=True) users = UserSerializer(many=True, read_only=True) class Meta: model = Locations fields = ['id', 'location_name', 'connections', 'users']
class JmxListSerializer(serializers.ModelSerializer): """ jmx列表查询 """ add_user = UserSerializer() class Meta: model = Jmxs exclude = ['jmx']
class TasksListSerializer(serializers.ModelSerializer): # add_user是Tasks模型中的字段 add_user = UserSerializer() class Meta: model = Tasks fields = "__all__"
def jwt_response_payload_handler(token, user=None, request=None): return { 'code': 200, 'msg': 'ok', 'data': { 'token': f"{settings.JWT_AUTH['JWT_AUTH_HEADER_PREFIX']} {token}", 'user': UserSerializer(user).data['id'] } }
def get_user(request): query = request.query_params if len(query) == 0: user = Users.objects.all() return Response(UserSerializer(instance=user, many=True).data, status=200) elif 'user_id' in query.keys() and len(query['user_id']) == 0: return Response({"error_message": "User ID not found!"}, status=400) elif 'user_id' in query.keys() and not query['user_id'][0].isdigit(): return Response({"error_message": "User ID should be an Integer!"}, status=400) elif 'user_id' in query.keys(): id = int(query['user_id']) user = Users.objects.filter(id=id).first() if user is None: return Response({"error_message": "User not found!"}) return Response(UserSerializer(instance=user).data, status=200) else: return Response({"error_message": "User Id not found!"}, status=400)
class RegistrationSerializerByCourse(serializers.ModelSerializer): user = UserSerializer() # course = CourseSerializer() class Meta: model = Registration fields = ( 'user', # 'course', 'cnt_abcense', )
class LocationSerializer(serializers.ModelSerializer): #is_fav = serializers.SerializerMethodField('getFav') users = UserSerializer(many=True, read_only=True) class Meta: model = Locations fields = [ 'id', 'location_name', 'users', ]
def login(request: Request) -> Response: err_response = Response(status=status.HTTP_401_UNAUTHORIZED) if 'username' not in request.data or 'password' not in request.data: return err_response username = request.data['username'] password = request.data['password'] user = authenticate(request, username=username, password=password) if user is None: return err_response django_login(request, user) serializer_data = UserSerializer(user).data serializer_data['csrftoken'] = csrf.get_token(request) return Response(serializer_data, status=status.HTTP_200_OK)
class ContentsSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Contents fields = ('id', "user", 'comment', "rating", 'created_at') def create(self, validated_data): contents = super(ContentsSerializer, self).create(validated_data) user = self.context['request'].user if not user.is_anonymous: contents.user = user contents.save() return contents
def post(self, request): email = request.data['email'] password = request.data['password'] try: user = User.objects.get(email=email) user = authenticate(request, email=email, password=password) login(request, user) except Exception as e: raise e return Response(UserSerializer(user).data)
def assertUserDetailEqual(self, content: str, user: User): # 时间正确性不能通过字符串比较 compare_fields = set(UserSerializer.Meta.fields) - {'last_login', 'date_joined', 'username', 'student_id'} json1 = json.loads(content) json2 = UserSerializer(user).data for field in compare_fields: self.assertEqual(json1[field], json2[field]) # 获取的数据和数据库中的数据在 json 意义上等价 self.assertDatetimeEqual(json1['date_joined'], user.date_joined) self.assertDatetimeEqual(json1['last_login'], user.last_login) if not (user.is_staff or user.is_superuser or int(user.id) == int(json1['id'])): self.assertEqual(json1['username'], '***') self.assertEqual(self, json1['student_id'], user.userprofile.student_id[0:4]) else: self.assertEqual(json1['username'], user.username) self.assertEqual(json1['student_id'], user.userprofile.student_id)
class TweetsSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Tweet fields = "__all__" def create(self, validated_data): user = self.context["request"].user return Tweet.objects.create(user=user, **validated_data) def update(self, instance, validated_data): if instance.user == self.context["request"].user: return super().update(instance, validated_data) else: error = {"message": "You can not edit another user's post"} raise serializers.ValidationError(error)
class RegistrationSerializer1(serializers.ModelSerializer): c_teacher = UserSerializer() student = serializers.SerializerMethodField() def get_student(self, obj): result_set = Registration.objects.filter(course=obj) return RegistrationSerializer(result_set, many=True).data class Meta: model = Course fields = ( 'c_id', 'c_name', 'c_code', 'c_teacher', 'cnt_sign', 'student', )
def user_create(request): try: name = request.data["name"] password = request.data["password"] username = request.data["username"] short_bio = request.data["short_bio"] email_id = request.data["email_id"] except KeyError: return Response( { "error_message": "Error! Please make sure all the Fields are provided properly." }, status=400) if len(name) == 0 or name is None: return Response({"error_message": "Name field cannot be empty"}, status=400) if len(password) < 6 or password is None: return Response( { "error_message": "Password length cannot be less than 6 characters!" }, status=400) does_username = Users.objects.filter(username=username).first() if does_username is not None: return Response( { "error_message": "Please Choose another Username as User with this Username already exists!" }, status=400) new_user = Users.objects.create(name=name, password=make_password(password), short_bio=short_bio, username=username, email_id=email_id) new_user.save() return Response(UserSerializer(instance=new_user).data, status=200)
class ThreadSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) thread = ResponseSerializer(many=True, read_only=True) class Meta: model = Thread fields = ( "id", "user", "title", "created_at", "thread", "is_active", "is_writable", ) def create(self, validated_data): thread = super(ThreadSerializer, self).create(validated_data) user = self.context['request'].user if not user.is_anonymous: thread.user = user thread.save() return thread
def signup(request: Request) -> Response: register_serializer = UserRegisterSerializer(data=request.data) if not register_serializer.is_valid(): return Response(register_serializer.errors, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(userprofile__student_id=register_serializer.validated_data['student_id']): # 判断注册的用户是微信小程序用户:姓名和学号与数据库中相同,且数据库中密码为空 # 如果满足条件,则将找到的用户的信息更新,然后返回 200 origin_wechat_user = User.objects.filter( userprofile__student_id=register_serializer.validated_data['student_id'], first_name=register_serializer.validated_data['first_name'], password='') if origin_wechat_user: u = origin_wechat_user[0] user_serializer = UserSerializer(u) user_serializer.update(u, register_serializer.validated_data) return Response(user_serializer.data, status=status.HTTP_200_OK) else: return Response(data={"student_id": "学号已存在"}, status=status.HTTP_400_BAD_REQUEST) u = register_serializer.save() user_serializer = UserSerializer(u) return Response(user_serializer.data, status=status.HTTP_201_CREATED)
class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = '__all__' stafalty = UserSerializer()
from utils.mail import send_reset_password_email from utils.permissions import login_required from utils.random import generate_uuid from utils.swagger import * from utils.validators import is_valid_password @swagger_auto_schema( method='POST', operation_summary='注册新用户', operation_description='成功注册新账户:返回 201\n' '成功绑定微信小程序账户:返回200\n' '失败(参数错误或不符合要求):返回 400\n' '注:注册以后不会自动登录', request_body=UserRegisterSerializer, responses={201: UserSerializer()} ) @api_view(['POST']) @csrf_exempt def signup(request: Request) -> Response: register_serializer = UserRegisterSerializer(data=request.data) if not register_serializer.is_valid(): return Response(register_serializer.errors, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(userprofile__student_id=register_serializer.validated_data['student_id']): # 判断注册的用户是微信小程序用户:姓名和学号与数据库中相同,且数据库中密码为空 # 如果满足条件,则将找到的用户的信息更新,然后返回 200 origin_wechat_user = User.objects.filter( userprofile__student_id=register_serializer.validated_data['student_id'], first_name=register_serializer.validated_data['first_name'], password='') if origin_wechat_user:
class ArticleSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Article fields = ('id', 'user', 'title', 'content', 'image')
class CourseSerializer(serializers.ModelSerializer): c_teacher = UserSerializer() class Meta: model = Course fields = ('c_id', 'c_code', 'c_name', 'c_teacher', 'cnt_sign')
def test_update_user(self): data = UserSerializer(self.user).data data.update({"username": "******"}) response = self.client.put(reverse("DetailUser", args=[self.user.id]), data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def get(self, request, pk): if not self.get_user(pk): Response('user Not Found in database', status=status.HTTP_404_NOT_FOUND) serializer = UserSerializer(self.get_user(pk)) return Response(serializer.data)
def get(self, request, **kwargs): try: # fetch provider with categories category_id = kwargs['category_id'] queryset = User.objects.filter( providercategorymappings__category__id=category_id) print('length1>>>', len(queryset)) if len(queryset) != 0: data_to_send = dict() print('length2>>>>', queryset[0]) _category = queryset[0].providercategorymappings.filter( category_id=category_id) print('length3>>>>', len(_category)) if len(_category) != 0: print('length4>>>>', _category[0]) _category_serializer = CategoriesSerializer( _category[0].category) data_to_send.update( {'category': _category_serializer.data}) data_to_send['category'].update({ 'image': base_url + data_to_send['category']['image'] }) data_to_send.update({'providers': []}) for d in queryset: print('location>>>', d.location_set.all()[0]) provider_dict = dict() provider_dict.update(UserSerializer(d).data) provider_dict.update({ 'location': LocationSerializer(d.location_set.all()[0]).data }) data_to_send['providers'].append(provider_dict) return Response(data={ 'msg': "Retrieved data", 'success': True, 'data': data_to_send }, status=status.HTTP_200_OK) else: return Response(data={ 'msg': "Category not found", 'success': False, 'data': '' }, status=status.HTTP_404_NOT_FOUND) else: return Response(data={ 'msg': "User not found", 'success': False, 'data': '' }, status=status.HTTP_404_NOT_FOUND) except Exception as e: print('error>>>>>>>>>', e.args) return Response(data={ 'msg': "Data not found", 'success': False, 'data': '' }, status=status.HTTP_404_NOT_FOUND)
def put(self, request, pk): user = self.get_user(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data)