def post(self, request, format=None): data = request.data try: email = data['email'] username = email[:email.find("@")] user = User.objects.create_user(username=username,email=email,password=data['password']) app_user = AppUser.objects.get(user=user) try: app_user.region = Region.objects.get(name='russia') app_user.save() except KeyError: print('No email', user) serializer = UserSerializer(app_user) return Response(serializer.data) except KeyError: try: telegram = data['telegram'] password = User.objects.make_random_password() user = User.objects.create_user(username=telegram,password=password) app_user = AppUser.objects.get(user=user) AppUser.objects.filter(user=user).update(telegram=telegram) serializer = UserSerializer(app_user) return Response(serializer.data) except IntegrityError as e: if 'unique constraint' in e.args[0]: data = {'details': 'User already exists'} return Response(data) except IntegrityError as e: if 'unique constraint' in e.args[0]: data = {'details': 'User already exists'} return Response(data)
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)
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)
def me(self, request): serializer = UserSerializer(request.user) if request.method == "PATCH": 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)
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)
def settimezone(request): if request.method == 'POST': user = request.user userSerializer = UserSerializer(user, many=False) return JsonResponse(userSerializer.data, safe=False) else: user = request.user userSerializer = UserSerializer(user, many=False) return JsonResponse(userSerializer.data, safe=False)
def get(self, request, **kwargs): if kwargs.get('user_id') is None: user_queryset = User.objects.all() user_queryset_serializer = UserSerializer(user_queryset, many=True) return Response(user_queryset_serializer.data, status=status.HTTP_200_OK) else: user_id = kwargs.get('user_id') user_serializer = UserSerializer(User.objects.get(user_id=user_id)) return Response(user_serializer.data, status=status.HTTP_200_OK)
def getadmin(request): print(request.method) if request.method == 'POST': user = User.objects.get(username=request.POST.get('username')) userSerializer = UserSerializer(user, many=False) return JsonResponse(userSerializer.data, safe=False) else: users = User.objects.filter(groups__name='admins') usersSerializer = UserSerializer(users, many=True) return JsonResponse(usersSerializer.data, safe=False)
def get(self, request, user_id=None): if user_id is not None: user = User.objects.get(id=user_id) serializer = UserSerializer(user, many=False) return Response(serializer.data) else: # users = User.objects.filter(procedure__id__startswith=request.GET.get("procedure_ID"), location__id=request.GET.get("location_ID")) users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data)
def me(self, request): user_profile = get_object_or_404(User, email=self.request.user.email) if request.method == 'GET': serializer = UserSerializer(user_profile) return Response(serializer.data, status=status.HTTP_200_OK) serializer = UserSerializer(user_profile, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
def me(self, request): user = get_object_or_404(User, pk=request.user.id) if request.method == "GET": serializer = UserSerializer(user, many=False) return Response(serializer.data) if request.method == "PATCH": serializer = UserSerializer(user, data=request.data, partial=True) 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)
def me(self, request): user = User.objects.get(username=request.user.username) if request.method == 'GET': serializer = UserSerializer(user) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'PATCH': serializer = UserSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(data=serializer.errors, status=status.HTTP_200_OK)
def user_list(request, format=None): "List all alerts, or create a new one" 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(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def user_list(request): if request.method == "GET": users = User.objects.all() ser = UserSerializer(users, many=True) return JsonResponse(ser.data, safe=False) elif request.method == "POST": data = JSONParser().parse(request) ser = UserSerializer(data=data) if ser.is_valid(): ser.save() return JsonResponse(ser.data, status=201) return JsonResponse(ser.errors, status=400)
def login_user(request): if request.method == 'GET': return Response(headers={ 'Location': 'http://login.typecraft.org?return_to=http://valex.typecraft.org' }, status=status.HTTP_302_FOUND) username = request.data.get('username') password = request.data.get('password') response = requests.post('http://login.typecraft.org/login', data={ 'username': username, 'password': password }) # Response expected to contain user information. If the user does not exist in the local database yet, # create it. If it doesn't exist remotely, redirect to signup with data if response.status_code == 200: response_data = response.json( ) # Expected to contain a DRF-serialized version of a user username = response_data.get('username') user = User.objects.filter(username=username).first() if not user: serializer = UserSerializer(data=response_data, context={'request': request}) if not serializer.is_valid(): return Response( { 'detail': 'Critical error, login server returned bad data.', 'source': response_data }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) new_user = serializer.save() login(request, new_user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: login(request, user) return Response(UserSerializer(user, context={ 'request': request }).data, status=status.HTTP_200_OK) else: return Response( { 'detail': 'Bad username or password', 'source': response.content }, status=status.HTTP_403_FORBIDDEN)
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)
def test_insert_single_user(self): test_data = { "first_name": "Test", "last_name": "User", "email": "*****@*****.**", "birthday": "01.02.1982" } response = self.client.post(reverse("users-insert-bulk"), test_data, 'json') actual_user = UserSerializer( User.objects.get(email="*****@*****.**")).data expected_user = UserSerializer(test_data).data self.assertEquals(response.status_code, status.HTTP_201_CREATED) self.assertEquals(actual_user, expected_user)
def add_groups(self, request, *args, **kwargs): user = self.get_object() data = UserSerializer(user, context={'request': request}).data user.groups.clear() for grupo in request.data['groups']: user.groups.add(Group.objects.get(name=grupo['name'])) for grupo in user.groups.all(): print(grupo) if grupo.name == "Profesional de Salud" and not hasattr( user, 'profesional_profile'): print('arigato') profesional = ProfesionalDeSalud(user=user) profesional.save() user.save() return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
def user_list(request): """ List all users, or create a new user. """ if request.method == 'GET': users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) 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(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
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)
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)
class PatientSerializer(Serializer): user = UserSerializer() date_of_birth = DateField() gender = CharField(max_length=1) mobileNumber = CharField(max_length=12) id = IntegerField(required=False) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) return Patient.objects.create(user=user, **validated_data) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = User.objects.all().filter( username=user_data.get("username")).first() user.first_name = user_data['first_name'] user.last_name = user_data.get('last_name') user.email = user_data.get('email') user.save() instance = instance.first() instance.user = user instance.date_of_birth = validated_data.get("date_of_birth") instance.gender = validated_data.get("gender") instance.mobileNumber = validated_data.get("mobileNumber") instance.save() return instance
class DoctorSerializer(Serializer): user = UserSerializer() qualification = CharField(max_length=50) specialisation = CharField(max_length=50) gender = CharField(max_length=1) title = CharField(max_length=50) experience = IntegerField() id = IntegerField(required=False) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) return Doctor.objects.create(user=user, **validated_data) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = User.objects.all().filter( username=user_data.get('username')).first() user.first_name = user_data['first_name'] user.last_name = user_data.get('last_name') user.email = user_data.get('email') user.save() instance = instance instance.user = user instance.qualification = validated_data.get("qualification") instance.experience = validated_data.get("experience") instance.specialisation = validated_data.get("specialisation") instance.gender = validated_data.get("gender") instance.title = validated_data.get("title") instance.save() return instance
def put(self, request: Request, pk, *args, **kwargs): classData = request.query_params.get('classData') remove = request.query_params.get('remove') originalUser: User = User.objects.get(uid__exact=pk) serializer: UserSerializer = UserSerializer(originalUser, data=request.data) if not serializer.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) serializer.save() print(serializer.data) if (classData is not None) and (remove is not None): user: User = User.objects.get(pk=pk) try: classData: Class = Class.objects.get(pk=classData) if remove == 'true': user.classes.remove(classData) print('class삭제 :', classData) else: user.classes.add(classData) print('class추가 :', classData) user.save() except Exception as e: print(e) pass return Response(self.serializer_class(originalUser).data)
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)
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)
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)
def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data }
def delete_users(): try: users = User.objects.filter(reminder_date=today) serializer = UserSerializer(users, many=True) except User.DoesNotExist: print(serializer.errors) return users.delete()
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)