def test_create_user(self): user = accounts_models.User() user.username = '******' user.email = '*****@*****.**' user.password = '******' user.is_superuser = False user.role = 'editor' user.display_name = 'OctBlog' user.biography = 'Octblog description' user.homepage_url = 'http://blog.igevin.info' user.save() created_user = accounts_models.User.objects.get(username='******') self.assertTrue(created_user is not None and created_user.email == '*****@*****.**')
def handle(self, *args, **options): students_per_section = options['students_per_section'] sections = structure_models.Section.objects.all().select_related( 'grade') year = '19' count = 0 for s in sections: students = [] student_infos = [] for i in range(students_per_section): username = get_username(year, count) count += 1 s_user = models.User(username=username) s_user.set_password('student1234') students.append(s_user) info = models.StudentInfo(gr_number=username, section_id=s.id) student_infos.append(info) # Create users models.User.objects.bulk_create(students) # Create infos models.StudentInfo.objects.bulk_create(student_infos) # Create profiles students = models.User.objects.all().order_by( '-id')[:students_per_section] student_infos = models.StudentInfo.objects.all().order_by( '-id')[:students_per_section] profiles = [] for student, info in zip(students, student_infos): profile = models.Profile(user_id=student.id, profile_type=models.Profile.STUDENT, student_info=info, fullname=student.username) profiles.append(profile) models.Profile.objects.bulk_create(profiles) self.stdout.write( f'Created {students_per_section} students per section.')
def test_create_post(self): post = main_models.Post() post.title = 'title' post.slug = 'slug' post.fix_slug = '1' post.abstract = 'abstract' post.raw = 'content' user = accounts_models.User() user.username = '******' user.password = '******' user.save() post.author = user post.category = 'category1' post.tags = ['tag1'] post.save() post = main_models.Post.objects.get(slug='slug') self.assertTrue(post is not None and post.title == 'title')
def create_user(self): validated_data = self.validated_data user = models.User( username=validated_data['fullname'].replace(' ', '')) user.set_password(validated_data['fullname'].replace(' ', '')) user.is_active = True user.save() # Create student info info = models.StaffInfo( date_hired=validated_data['date_hired'], address=validated_data['address'], gender=validated_data['gender'], ) info.save() # Create profile profile = models.Profile( user_id=user.id, fullname=validated_data['fullname'], contact=validated_data['contact'], staff_info_id=info.id, profile_type=validated_data['profile_type'], ) profile.save()
def create_user(self): validated_data = self.validated_data user = models.User(username=validated_data['gr_number']) user.set_password(validated_data['gr_number']) user.is_active = True user.save() # Create student info info = models.StudentInfo( gr_number=validated_data['gr_number'], section_id=validated_data['section_id'], date_enrolled=validated_data['date_enrolled'], date_of_birth=validated_data['date_of_birth'], address=validated_data['address'], guardian_name=validated_data['guardian_name'], guardian_contact=validated_data['guardian_contact'], gender=validated_data['gender']) info.save() # Create profile profile = models.Profile(user_id=user.id, fullname=validated_data['fullname'], student_info_id=info.id, profile_type=models.Profile.STUDENT) profile.save()
def create(self, data: dict) -> accounts_models.User: """ register a user in the system weedmtach, this method validate all information and if everything is correct register the user, this method raises a exception when the username exist, as well as the mail exist. :param data: contain all information to register a user in weedmatch first_name, username, email, password, latitud, longitud, age, sex :type data: dict :return: Model User. :raises: ValueError """ print(data) #validation of the date birth date date = data['age'][:10] if not date and not data.get('age'): raise ValueError('{"age":"' + str(_("The date field can not be empty")) + '"}') match = re.match(r'([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))', date) if not match: raise ValueError('{"age":"' + str(_("The date you entered is not valid")) + '"}') try: data['age'] = datetime.strptime(date, '%Y-%m-%d') except Exception as e: raise ValueError('{"age":"' + str(_("The day is out of range per month")) + '"}') validator = accounts_validations.RegisterUserValidate(data) if validator.validate() is False: errors = validator.errors() for value in errors: errors[value] = validator.change_value(errors[value]) raise ValueError(errors) #validation for the username if accounts_models.User.objects.filter( username=data.get('username')).exists(): raise ValueError( '{"username":"******"The username exists, please enter another username")) + '"}') #validation for the email if not re.match(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', data.get('email')): raise ValueError('{"email":"' + str(_("Please enter a valid email address")) + '"}') if accounts_models.User.objects.filter( email=data.get('email')).exists(): raise ValueError( '{"email":"' + str(_("Mail exists, please enter another email")) + '"}') """ necesito para la api en produccion el googlemaps api key del cliente """ # Requests to GoogleMap Api gmaps = googlemaps.Client(key=settings.GOOGLE_MAPS_KEY) try: reverse_geocode_result = gmaps.reverse_geocode( (float(data.get('latitud')), float(data.get('longitud')))) except googlemaps.exceptions.ApiError: raise ValueError('{"googlemaps": "' + str(_("The key that was used does not work")) + '"}') if len(reverse_geocode_result) == 1: direction = reverse_geocode_result[0].get('formatted_address') for lists in reverse_geocode_result[0].get('address_components'): country = accounts_models.Country.objects.filter( name=lists.get('long_name')) if not len(country) == 0: break else: direction = reverse_geocode_result[1].get('formatted_address') count = len(reverse_geocode_result) - 1 country_map = reverse_geocode_result[count].get( 'formatted_address') try: country = accounts_models.Country.objects.filter( name=country_map) except accounts_models.Country.DoesNotExist: raise ValueError( '{"country":"' + str(_("The country is not registered in the system")) + '"}') user = accounts_models.User() data["country_id"] = country[0].id data["direction"] = direction data["last_name"] = "" for key in data.keys(): if key == 'password': data[key] = make_password(data[key]) setattr(user, key, data[key]) try: user.save(force_insert=True) except Exception as e: raise ValueError( '{"user":"******"An error occurred while saving the user")) + '"}') print(user) # add group weedmatch group = Group.objects.get(name='WeedMatch') user.groups.add(group) return user
def post(self, request, format=None): # url para cambiar el code por un nuevo access_token access_token_url = 'https://graph.facebook.com/v2.8/oauth/access_token' # url para obtener datos de perfil graph_api_url = 'https://graph.facebook.com/v2.8/me?' \ 'fields=id,last_name,first_name,email,hometown,picture.type(normal)' # obtener nuevo access_token redirect_uri = request.data.get('redirectUri', None) if redirect_uri is None: return Response(_("Missing 'redirectUri' in request"), status=status.HTTP_400_BAD_REQUEST) code = request.data.get('code') if code is None or code == "": return Response(_("Missing 'code' in request"), status=status.HTTP_400_BAD_REQUEST) params = { 'client_id': settings.FACEBOOK_CLIENT, 'redirect_uri': redirect_uri, 'client_secret': settings.FACEBOOK_SECRET, 'code': code } r = requests.get(access_token_url, params=params) try: access_token = json.loads(r.text) except Exception as e: return Response("error comunicationg with Facebook: %s" % str(e), status=status.HTTP_400_BAD_REQUEST) var_access_token = access_token.get("access_token", None) if var_access_token is None: return Response("error comunicationg with Facebook: %s" % str(r.text), status=status.HTTP_400_BAD_REQUEST) params = { 'client_id': settings.FACEBOOK_CLIENT, 'grant_type': "fb_exchange_token", 'client_secret': settings.FACEBOOK_SECRET, 'fb_exchange_token': var_access_token } # obtener datos de perfil r = requests.get(access_token_url, params=params) access_token = json.loads(r.text) r = requests.get(graph_api_url, params=access_token) profile = json.loads(r.text) user = accounts_models.User.objects.filter( facebook_id=profile["id"]).first() if user: if user.is_active == False: return Response(_("Your account has been disabled."), status=status.HTTP_403_FORBIDDEN) token, created = Token.objects.get_or_create(user=user) data = { 'registered': True, 'token': token.key, 'user': { "id": user.id, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "facebook_picture_url": user.facebook_picture_url, "hometown": user.hometown } } return Response(data, status=status.HTTP_200_OK) logger.info(profile) user = accounts_models.User() user.facebook_id = profile["id"] user.username = profile["id"] user.first_name = profile["first_name"] user.last_name = profile["last_name"] user.hometown = profile["hometown"][ "name"] if "hometown" in profile.keys() else "" user.email = profile["email"] if 'email' in profile else str( profile['id'] + '@facebook.com') try: user.facebook_picture_url = profile['picture']['data']['url'] except KeyError as e: logger.error( "Error getting facebook profile picture from result: %s" % str(e)) except Exception as e: logger.error("Error getting facebook profile picture: %s" % str(e)) user.save() token, created = Token.objects.get_or_create(user=user) data = { 'registered': True, 'token': token.key, 'user': { "id": user.id, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "is_staff": user.is_staff, "facebook_picture_url": user.facebook_picture_url, "hometown": user.hometown } } return Response(data, status=status.HTTP_200_OK)
def post(self, request, format=None): # url para obtener datos de perfil graph_api_url = 'https://graph.facebook.com/v2.8/me?' \ 'fields=id,last_name,first_name,email,hometown,picture.type(normal)' # obtener nuevo access_token access_token = request.data.get('access_token') if access_token is None or access_token == "": return Response(_("Missing 'access_token' in request"), status=status.HTTP_400_BAD_REQUEST) data = {"access_token": access_token} r = requests.get(graph_api_url, params=data) if r.status_code != 200: return Response(r.text, status=status.HTTP_400_BAD_REQUEST) profile = json.loads(r.text) user = accounts_models.User.objects.filter( facebook_id=profile["id"]).first() if user: if user.is_active == False: return Response(_("Your account has been disabled"), status=status.HTTP_403_FORBIDDEN) token, created = Token.objects.get_or_create(user=user) data = { 'registered': True, 'token': token.key, 'user': { "id": user.id, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "is_staff": user.is_staff, "is_superuser": user.is_superuser, "facebook_picture_url": user.facebook_picture_url, "hometown": user.hometown } } return Response(data, status=status.HTTP_200_OK) logger.info(profile) user = accounts_models.User() user.facebook_id = profile["id"] user.username = profile["id"] user.first_name = profile["first_name"] user.last_name = profile["last_name"] user.hometown = profile["hometown"][ "name"] if "hometown" in profile.keys() else "" user.email = profile["email"] if 'email' in profile else str( profile['id'] + '@facebook.com') try: user.facebook_picture_url = profile['picture']['data']['url'] except KeyError as e: logger.error( "Error getting facebook profile picture from result: %s" % str(e)) except Exception as e: logger.error("Error getting facebook profile picture: %s" % str(e)) user.save() token, created = Token.objects.get_or_create(user=user) data = { 'registered': True, 'token': token.key, 'user': { "id": user.id, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "is_staff": user.is_staff, "facebook_picture_url": user.facebook_picture_url, "hometown": user.hometown } } return Response(data, status=status.HTTP_200_OK)