Exemplo n.º 1
0
 def put(self, request, *args, **kwargs):
     user = request.data["pk"]
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return self.update(request, *args, **kwargs)
Exemplo n.º 2
0
 def post(self, request, format=None):
     data = JSONParser().parse(request)
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 3
0
 def me(self, request):
     serializer = UserSerializer(request.user,
                                 data=request.data,
                                 partial=True)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 4
0
def user_detail(request, pk):
    """
    get, update, or delete a specific user
    :param request: get,put,delete
    :param pk: user_id (primary key)
    :return: response
    """

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserSerializer(user, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 5
0
    def post(self, request, *args, **kwargs):
        """
        Create a new user and a basic profile for the user.
        Return the user profile id and user data.

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        user_serializer = UserSerializer(data=request.data)

        # If the data isn't valid we return the error messages
        if not user_serializer.is_valid():
            return Response(user_serializer.errors, status=400)

        # Otherwise we save the user and create a profile for the user
        user_serializer.save()
        user_profile = Profile(
            user=user_serializer.instance
        )
        user_profile.save()

        ret = user_serializer.to_representation(user_serializer.instance)
        ret['profile_id'] = user_profile.id
        return Response(ret, status=201)
Exemplo n.º 6
0
 def put(self, request, id):
     user = self.get_object(id)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 7
0
    def post(self, request):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 8
0
 def put(self, request, pk, format=None):
     user = self.get_object(pk)
     serializer = UserSerializer(user, data=request.data, partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
def activate(request, pk):
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        raise Http404

    serializer = UserSerializer(user, data=request.data, partial=True)
    if serializer.is_valid():
        if not request.data.get('activation_code') or not request.data.get(
                'password'):
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        if user.activation_code != request.data.get('activation_code'):
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        if len(user.password) != 0:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        serializer.save()
        user.set_password(request.data['password'])
        user.save()
        return Response(serializer.data)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 10
0
def create_user(request):
    if not request.body:
        return HttpResponse(status=404)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        try:
            user = User()
            validate_email(data['email'])
        except ValidationError:
            return HttpResponse(status=400)
        users = User.objects.all()
        if not users:
            serializer = UserSerializer(user, data=data)
            if serializer.is_valid():
                serializer.save()
                return HttpResponse(status=202)  #First User
            return HttpResponse(status=400)
        else:
            for u in users:
                if data['email'] == u.get_email():
                    return HttpResponse(status=400)
            serializer = UserSerializer(user, data=data)
            if serializer.is_valid():
                serializer.save()
                return HttpResponse(status=202)
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=404)
Exemplo n.º 11
0
 def put(self, request, id, format=None):
     user = self.get_object(id)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 12
0
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return JsonResponse({'Status': False, 'Error': 'Log in required'}, status=403)
        # проверяем обязательные аргументы

        if 'password' in request.data:
            errors = {}
            # проверяем пароль на сложность
            try:
                validate_password(request.data['password'])
            except Exception as password_error:
                error_array = []
                # noinspection PyTypeChecker
                for item in password_error:
                    error_array.append(item)
                return JsonResponse({'Status': False, 'Errors': {'password': error_array}})
            else:
                request.user.set_password(request.data['password'])

        # проверяем остальные данные
        user_serializer = UserSerializer(request.user, data=request.data, partial=True)
        if user_serializer.is_valid():
            user_serializer.save()
            return JsonResponse({'Status': True})
        else:
            return JsonResponse({'Status': False, 'Errors': user_serializer.errors})
Exemplo n.º 13
0
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
 def put(self, request, uid, format=None):
     user = self._get_object(uid)
     serializer = UserSerializer(user, data=request.DATA)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 15
0
def add_user(request):
	serializer = UserSerializer(data = request.data)
	if serializer.is_valid():
		serializer.save()
		return Response(serializer.data, status = status.HTTP_201_CREATED)
	else:
		return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
Exemplo n.º 16
0
    def create(self, request):
        if all(value != None for value in request.data.values()):
            email = request.data.get("email")
            username = request.data.get("username")
            password = request.data.get("password") or request.data.get(
                "password1")
            logger.info(f"TRYING SERIALIZE NEW USER: {request.data}")

            serializer = UserSerializer(data={
                "username": username,
                "email": email,
                "password": password
            })
            if serializer.is_valid():
                serializer.save()
                logger.info(f"NEW USER CREATED: {serializer.data} ")
                new_user = User.objects.get(email=email, username=username)
                if UserProfile.objects.create(user=new_user,
                                              id=new_user.id,
                                              user_courses=[]):
                    logger.info(f"USER PROFILE WAS CREATED - {new_user.id}")
                    return Response(serializer.data,
                                    status=status.HTTP_201_CREATED)
            else:
                logger.error(
                    f"NEW USER WAS NOT CREATED {serializer.data} BECAUSE OF {serializer.errors}"
                )
                return Response(serializer.errors,
                                status=status.HTTP_412_PRECONDITION_FAILED)
        else:
            logger.error(
                f"NEW USER WAS NOT CREATED - SOME EMPTY INPUT FIELDS: {request.data}"
            )
            return Response(status=status.HTTP_412_PRECONDITION_FAILED)
Exemplo n.º 17
0
 def post(self, request):
     data = json.loads(request.query_params.get('data', {}))
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save(password=data.get("user_password"))
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 18
0
    def partial_update(self, request, pk=None):
        order = Order.objects.all().get(id=pk)

        seller_id = order.seller_id
        user_id = order.user_id
        car_id = order.car_id

        car = Car.objects.all().get(id=car_id)

        buyer = User.objects.all().get(id=user_id)
        buyer.balance = buyer.balance - car.price
        buyer_serializer = UserSerializer(buyer,
                                          data=model_to_dict(buyer),
                                          partial=True)
        buyer_serializer.is_valid(raise_exception=True)
        buyer_serializer.save()

        seller = User.objects.all().get(id=seller_id)
        seller.balance = seller.balance + car.price
        seller_serializer = UserSerializer(seller,
                                           data=model_to_dict(seller),
                                           partial=True)
        seller_serializer.is_valid(raise_exception=True)
        seller_serializer.save()

        order.status = 1
        serializer = OrderSerializer(order,
                                     data=model_to_dict(order),
                                     partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
Exemplo n.º 19
0
    def post(self, request):
        username = request.data['username']
        center_id = request.data['center_id']

        if User.objects.filter(username=username).count() == 0:
            password = make_password('123')
            data = {
                'username': username,
                'password': password,
                'center_id': center_id,
                'status': 1
            }
            serializer = UserSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                response = {
                    'code': 1,
                    'data': serializer.data,
                }
                return Response(response)
            else:
                return Response(serializer.errors)
        else:
            response = {
                'code': 0,
                'message': '用户名已存在'
            }
            return Response(response)
Exemplo n.º 20
0
 def post(self, request):
     data = JSONParser().parse(request)
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return JSONResponse(serializer.data, status=201)
     return JSONResponse(serializer.errors, status=400)
Exemplo n.º 21
0
 def post(self, request):
     uid = request.data['id']
     status = request.data['status']
     data = {
         'id': uid,
         'status':status
     }
     try:
         user = User.objects.get(id=uid)
     except:
         response = {
             'code': 0,
             'message': '用户id不存在',
         }
         return Response(response)
     else:
         serializer = UserSerializer(data=data, instance=user)
         if serializer.is_valid():
             serializer.save()
             response = {
                 'code': 1,
                 'data': serializer.data,
             }
             return Response(response)
         else:
             return Response(serializer.errors)
Exemplo n.º 22
0
 def put(self, request):
     uid = request.data['id']
     password = make_password(request.data['password'])
     new_password = make_password(request.data['new_password'])
     data = {
         'id': uid,
         'password': new_password
     }
     try:
         user = User.objects.get(id=uid, password=password)
     except:
         response = {
             'code': 0,
             'message': '原密码错误',
         }
         return Response(response)
     else:
         serializer = UserSerializer(data=data, instance=user)
         if serializer.is_valid():
             serializer.save()
             response = {
                 'code': 1,
                 'data': serializer.data,
             }
             return Response(response)
         else:
             return Response(serializer.errors)
Exemplo n.º 23
0
 def create(self, request, *args, **kwargs):
     """
     Override create method to hash the user's password
     :param request: POST request with user data
     :param args: none
     :param kwargs: none
     :return: If there is duplicate user, it returns 400. Otherwise, returns 201.
     """
     password = request.data['password']
     hashed_password = pl_hash.django_pbkdf2_sha256.hash(password)
     data = {
         'email': request.data['email'],
         'first_name': request.data['first_name'],
         'last_name': request.data['last_name'],
         'password_hash': hashed_password,
         'color_pref': request.data['color_pref'],
         'school': request.data['school'],
     }
     serializer = UserSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 24
0
def sign_up(request):
    if request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 25
0
 def put(self, request, format=None):
   email = request.query_params['email']
   user = self.get_user(email)
   serializer = UserSerializer(user, data=request.data)
   if serializer.is_valid():
     serializer.save()
     return Response(serializer.data, status=status.HTTP_200_OK)
   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 26
0
 def put(self, request, user_id):
     data = json.loads(request.body.decode('utf-8'))
     user = self.get_object(user_id)
     serializer = UserSerializer(user, data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors)
Exemplo n.º 27
0
 def post(self, request, userId):
     data = json.loads(request.POST.get('data', '{}'))
     user_details = User.objects.get(user_id=userId)
     serializer = UserSerializer(user_details, data=data)
     if serializer.is_valid():
         serializer.save()
         return JsonResponse(serializer.data)
     return JsonResponse(serializer.errors, status=400)
Exemplo n.º 28
0
def sign_up_user(request):
    if request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'Message': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 29
0
def register(request):
    serializer = UserSerializer(data=request.data)
    serializer_profile = ProfileSerializer(data=request.data.get("profile"))
    if serializer.is_valid() and serializer_profile.is_valid():
        serializer.save()
        serializer_profile.save()
        return Response(serializer_profile.data)
    return Response(serializer.errors)
Exemplo n.º 30
0
 def delete(self, request, *args, **kwargs):
     user = request.data["pk"]
     serializer = UserSerializer(user, data=request.data)
     #user.delete()
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return self.destroy(request, *args, **kwargs)
Exemplo n.º 31
0
 def partial_update(self, request, pk=None):
     user = User.objects.all().get(id=pk)
     if "password" in request.data:
         request.data["password"] = make_password(request.data["password"],
                                                  None, 'pbkdf2_sha256')
     serializer = UserSerializer(user, data=request.data, partial=True)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(serializer.data)
Exemplo n.º 32
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         response_data = serializer.data
         response_data["success"] = "True"
         response_data["message"] = "Settings created successfully."
         return Response(response_data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 33
0
 def me_retrieve_patch(self, request):
     user = request.user
     if request.method == 'PATCH':
         serializer = UserSerializer(user, data=request.data, partial=True)
         serializer.is_valid(raise_exception=True)
         serializer.save(role=request.user.role)
         return Response(serializer.data, status=status.HTTP_200_OK)
     serializer = UserSerializer(user)
     return Response(serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 34
0
 def put(self, request, pk, format=None):
     try:
         user = get_object(User, pk)
         serializer = UserSerializer(user, data=request.data, partial=True)
         if serializer.is_valid(raise_exception=True):
             serializer.save()
             return Response(serializer.data)
     except ResourceNotFoundException as exc:
         return Response(data=exc.data, status=exc.status_code)
Exemplo n.º 35
0
def user_list(request):

    if request.method == 'GET':
        user = User.objects.all()
        serializer = UserSerializer(user, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Exemplo n.º 36
0
def register(req):
    phone = req.session.get("phone", "")
    password = req.session.get('password', "")
    if not phone:
        return SimpleResponse(False, "请先验证手机")
    else:
        del req.session['phone']
    req.data["phone_number"] = phone
    req.data['password'] = password
    ser = UserSerializer(data=req.data)
    if ser.is_valid():
        ser.save()
        return SimpleResponse(True)
    else:
        return SimpleResponse(False, ser.error_messages)
Exemplo n.º 37
0
Arquivo: views.py Projeto: leohahn/TIM
def user_list(request, format=None):
    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            if (0 == User.objects.filter(phoneNr= serializer.validated_data['phoneNr']).count()):
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        print (serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 38
0
    def post(self, request):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            credentials = {
                'email': serializer.validated_data['email'],
                'password': serializer.validated_data['password']
            }

            token = get_user_token(credentials)
            data = {'token': token}

            return Response(data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 39
0
def user_list(request):
    """
    List all users, or create a new one
    :param request:
    :return:
    """

    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = UserSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 40
0
def user(request, email):
	try:
		user = User.objects.get(email=email)
	except User.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method == 'GET':
		serializer = UserSerializer(user)
		return Response(serializer.data)

	elif request.method == 'PUT':
		serializer = UserSerializer(user, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method == 'DELETE':
		user.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 41
0
Arquivo: views.py Projeto: leohahn/TIM
def user_detail(request, name, format=None):
    try:
        user = User.objects.get(username=name)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            print(serializer.data)
            return Response(serializer.data)
        print(serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 42
0
def user_detail(request, pk):

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
Exemplo n.º 43
0
def user_detail(request, id):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        user = User.objects.get(id=id)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
Exemplo n.º 44
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 45
0
serializer = UserSerializer(data=data)

#Deserialize Report
stream = BytesIO(contentReport)
data = JSONParser().parse(stream)

serializer = ReportSerializer(data=data)

#Deserialize ImageReport
stream = BytesIO(contentImageReport)
data = JSONParser().parse(stream)

serializer = ImageReportSerializer(data=data)

#Deserialize Comment
stream = BytesIO(contentComment)
data = JSONParser().parse(stream)

serializer = CommentSerializer(data=data)



#Check generic valid
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()