Here are the examples of the python api django.contrib.auth.models.User.objects.all taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
57 Examples
3
View Complete Implementation : ftpserver.py
Copyright Apache License 2.0
Author : liyao001
Copyright Apache License 2.0
Author : liyao001
def load_user_table():
try:
all_user = User.objects.all()
auth = DummyMD5Authorizer()
ws = get_config('env', 'workspace')
for user in all_user:
user_directory = os.path.join(ws, str(user.id), 'uploads')
if not os.path.exists(user_directory):
os.makedirs(user_directory)
auth.add_user(user.username, user.pastword, user_directory, perm='elradfmw')
return auth
except Exception as e:
print(e)
return 0
3
View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : overshard
Copyright BSD 2-Clause "Simplified" License
Author : overshard
def get_queryset(self):
if self.request.user.is_superuser:
queryset = User.objects.all()
else:
queryset = User.objects.filter(id=self.request.user.id)
return queryset
3
View Complete Implementation : tests.py
Copyright MIT License
Author : fga-eps-mds
Copyright MIT License
Author : fga-eps-mds
def test_post_user_persist_db(client):
""" Test persist users in database """
url = reverse('users:users')
data = {'username': "username", 'email': "[email protected]",
'pastword': "pastword"}
client.post(url, data=data)
users = User.objects.all()
astert users.count() == 1
3
View Complete Implementation : mainWindowManager.py
Copyright MIT License
Author : ZedObaia
Copyright MIT License
Author : ZedObaia
def printUsers(self):
allUsers = User.objects.all()
print("Now we have {} users".format(len(allUsers)))
print("Users : ")
for user in allUsers:
print(user.username)
3
View Complete Implementation : notifications.py
Copyright GNU General Public License v3.0
Author : treussart
Copyright GNU General Public License v3.0
Author : treussart
def email(satle, plain_body, html_body): # pragma: no cover
users = User.objects.all()
if settings.DEFAULT_FROM_EMAIL:
try:
for user in users:
if user.is_superuser:
try:
user.email_user(satle, plain_body, html_message=html_body)
except AttributeError:
logger.exception("Error in sending email")
except SMTPException:
logger.exception("Error in sending email")
except ConnectionRefusedError:
logger.exception("Error in sending email")
3
View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : elastic
Copyright BSD 3-Clause "New" or "Revised" License
Author : elastic
def render_user_view(request):
def something_expensive():
with elasticapm.capture_span("something_expensive", "code"):
for i in range(100):
users = list(User.objects.all())
return users
return render(request, "list_users.html", {"users": something_expensive})
3
View Complete Implementation : clear_exchange_balances.py
Copyright GNU General Public License v3.0
Author : msantl
Copyright GNU General Public License v3.0
Author : msantl
def handle(self, *args, **options):
users = User.objects.all()
for user in users:
self.stdout.write("Removing balances for %s" % (user.email))
exchange_accounts = ExchangeAccount.objects.filter(user=user)
for exchange_account in exchange_accounts:
exchange_balances = ExchangeBalance.objects.filter(
exchange_account=exchange_account)
for exchange_balance in exchange_balances:
exchange_balance.delete()
3
View Complete Implementation : create_usersettings.py
Copyright MIT License
Author : Arx-Game
Copyright MIT License
Author : Arx-Game
def handle(self, *args, **options):
"handle command line"
for u in User.objects.all():
try:
s = UserSettings.objects.get(user=u)
except UserSettings.DoesNotExist:
s = UserSettings(user=u, settings=DEFAULT_USER_SETTINGS)
s.save()
3
View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : texta-tk
Copyright GNU General Public License v3.0
Author : texta-tk
def create_dataset_access_permission_and_propagate(dataset, access):
content_type = ContentType.objects.get_for_model(Dataset)
permission = Permission.objects.create(
codename='can_access_dataset_' + str(dataset.id),
name='Can access dataset {0} -> {1}'.format(dataset.index, dataset.mapping),
content_type=content_type,
)
permission.save()
if access == 'public':
for user in User.objects.all():
user.user_permissions.add(permission)
3
View Complete Implementation : managers.py
Copyright MIT License
Author : guandjoy
Copyright MIT License
Author : guandjoy
def reorder_by(self, field):
users = User.objects.all()
for user in users:
qs = self.get_queryset().filter(owner=user).exclude(Q(satle=None)| Q(satle=""), Q(content=None) | Q(content="")).order_by(field)
for index, note in enumerate(qs.filter(pinned=True)):
# pinned on top
note.order = index
note.save()
for index, note in enumerate(qs.filter(pinned=False)):
# not pinned
note.order = index
note.save()
3
View Complete Implementation : views.py
Copyright MIT License
Author : wise-team
Copyright MIT License
Author : wise-team
def profile_list(request, template_name="profiles/profiles.html"):
if request.user.is_staff:
users = User.objects.all()
else:
users = User.objects.filter(is_active=True)
return render(request, template_name, {"users": users})
3
View Complete Implementation : users_api.py
Copyright GNU General Public License v2.0
Author : welliamcao
Copyright GNU General Public License v2.0
Author : welliamcao
@api_view(['GET', 'POST' ])
def user_list(request,format=None):
"""
List all order, or create a server astets order.
"""
if request.method == 'GET':
snippets = User.objects.all()
serializer = serializers.UserSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
if not request.user.has_perm('OpsManage.add_user'):
return Response(status=status.HTTP_403_FORBIDDEN)
serializer = serializers.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)
3
View Complete Implementation : test_queryset.py
Copyright MIT License
Author : ivelum
Copyright MIT License
Author : ivelum
def test_apply_search(self):
qs = User.objects.all()
try:
qs = apply_search(qs, 'groups = None')
qs.count()
except Exception as e:
self.fail(e)
3
View Complete Implementation : create_member_for_superusers.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def handle(self, *args, **options):
for user in User.objects.all():
if user.is_superuser:
signals.post_save.disconnect(Member.create, sender=Member)
member = Member.objects.create(user=user, first_name='super', last_name='duper', email=user.email,
addr_street='superstreet', addr_zipcode='8000',
addr_location='SuperCity', phone='012345678', confirmed=True)
member.save()
user.member = member
user.save()
signals.post_save.connect(Member.create, sender=Member)
3
View Complete Implementation : models.py
Copyright MIT License
Author : ArnaudLevaufre
Copyright MIT License
Author : ArnaudLevaufre
def __call__(self, request, *args, **kwargs):
key = request.GET.get('key')
if not key:
return HttpResponse(status=401)
for user in User.objects.all():
if key == str(user.profile.api_key):
break
else:
return HttpResponse(status=401)
return super().__call__(request, *args, **kwargs)
3
View Complete Implementation : signals_test.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
Copyright BSD 3-Clause "New" or "Revised" License
Author : mitodl
def test_profile_creation(self):
"""
Tests that if a user is created, the profile for such user is created
"""
# there are no users
astert len(User.objects.all()) == 0
astert len(Profile.objects.all()) == 0
# the creation of a user triggers the creation of a profile
user = User.objects.create(username='test', pastword='test')
astert len(User.objects.all()) == 1
astert len(Profile.objects.all()) == 1
astert Profile.objects.all()[0].user == user
# saving again the user does not create another profile
user.first_name = 'the'
user.save()
astert len(User.objects.all()) == 1
astert len(Profile.objects.all()) == 1
3
View Complete Implementation : rule_is_tests.py
Copyright MIT License
Author : excitedleigh
Copyright MIT License
Author : excitedleigh
@pytest.mark.django_db
def test_current_user():
u1 = UserFactory()
u2 = UserFactory()
astert current_user.check(u1, u1)
astert not current_user.check(u1, u2)
astert set(current_user.filter(u1, User.objects.all())) == {u1}
3
View Complete Implementation : test_basic.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
def test_swappable_user(self):
"The current user model can be swapped out for another"
self.astertEqual(get_user_model(), CustomUser)
with self.astertRaises(AttributeError):
User.objects.all()
3
View Complete Implementation : create_default_project.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
def handle(self, *args, **options):
print "Task started ..."
# Get all the users
for user in queryset_iterator(User.objects.all()):
# For each user get the forms which are projectless
for form in queryset_iterator(XForm.objects
# JNM TEMPORARY
#.select_related('projectxform')
.filter(projectxform=None,
user=user)):
# Create the default project
self.create_and_astign_project(user, form)
print "Task completed ..."
3
View Complete Implementation : inspect_database.py
Copyright GNU Affero General Public License v3.0
Author : SpottedBot
Copyright GNU Affero General Public License v3.0
Author : SpottedBot
def inspect_executer():
tables = {
"FacebookUser": len(FacebookUser.objects.all()),
"User": len(User.objects.all()),
"Moderator": len(Moderator.objects.all()),
"WorkHour": len(WorkHour.objects.all()),
"Spotted": len(Spotted.objects.all()),
"PendingSpotted": len(PendingSpotted.objects.all())
}
text = ""
count = 0
for key, value in tables.items():
text += "\n{} has {} rows".format(key, value)
count += value
text += "\n\nTotal editable rows: {}".format(count)
return text
3
View Complete Implementation : views.py
Copyright MIT License
Author : fga-eps-mds
Copyright MIT License
Author : fga-eps-mds
def get(self, request, format=None):
users = User.objects.all()
serializer = UserCreateSerializer(users, many=True)
return Response(serializer.data)
3
View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : texta-tk
Copyright GNU General Public License v3.0
Author : texta-tk
@login_required
@user_pastes_test(lambda u: u.is_superuser)
def index(request):
indices = ES_Manager.get_indices()
indices = sorted(indices, key=lambda x: x['index']) # sort alphabetically
datasets = get_datasets(indices=indices)
users = User.objects.all()
users = annotate_users_with_permissions(users, datasets)
template = loader.get_template('permission_admin.html')
allowed_datasets = Datasets().get_allowed_datasets(request.user)
language_models =Task.objects.filter(task_type=TaskTypes.TRAIN_MODEL.value).filter(status__iexact=Task.STATUS_COMPLETED).order_by('-pk')
return HttpResponse(template.render({'users':users,'datasets':datasets,'indices':indices,'STATIC_URL':STATIC_URL,'URL_PREFIX':URL_PREFIX, 'allowed_datasets': allowed_datasets, 'language_models': language_models},request))
3
View Complete Implementation : export_users.py
Copyright GNU General Public License v3.0
Author : amfoss
Copyright GNU General Public License v3.0
Author : amfoss
def handle(self, *args, **options):
users = User.objects.all()
usersData = []
for user in users:
userArr = []
userArr.append(user.username)
userArr.append(user.email)
userArr.append(user.first_name)
userArr.append(user.last_name)
usersData.append(userArr)
with open('users.csv', 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(usersData)
csvFile.close()
3
View Complete Implementation : vUser.py
Copyright GNU General Public License v2.0
Author : welliamcao
Copyright GNU General Public License v2.0
Author : welliamcao
@login_required
@permission_required('auth.change_user',login_url='/noperm/')
def user(request):
if request.method == "GET":
try:
userList = User.objects.all()
except Exception,e:
userList = []
return render_to_response('vmUser/user_manage.html',{"user":request.user,"localtion":[{"name":"首页","url":'/'},{"name":"用户管理","url":'/usermanage/?op=list'}],
"userList":userList},
context_instance=RequestContext(request))
3
View Complete Implementation : managers.py
Copyright MIT License
Author : guandjoy
Copyright MIT License
Author : guandjoy
def remove_order_gaps(self):
""" Remove all gaps in ordering which somehow occured
Remove the root cause of this issue """
users = User.objects.all()
for user in users:
qs = self.get_queryset().filter(owner=user).order_by('order')
for index, note in enumerate(qs):
print(f'Old order: {note.order}. New order: {index + 1}')
note.order = index + 1
note.save()
3
View Complete Implementation : test_views.py
Copyright MIT License
Author : wise-team
Copyright MIT License
Author : wise-team
def setUp(self):
initial_data.load()
for user in User.objects.all():
profile = Profile.objects.create(user=user)
profile.save()
settings.RESTRICT_PACKAGE_EDITORS = True
self.test_add_url = reverse('add_package')
self.test_edit_url = reverse('edit_package',
kwargs={'slug': 'testability'})
self.login = self.client.login(username='user', pastword='user')
self.user = User.objects.get(username='user')
3
View Complete Implementation : users.py
Copyright GNU General Public License v2.0
Author : welliamcao
Copyright GNU General Public License v2.0
Author : welliamcao
def get_users(self,request=None):
userList = []
for ds in User.objects.all() :
data = self.convert_to_dict(ds)
data.pop('pastword')
userList.append(data)
return userList
3
View Complete Implementation : views.py
Copyright MIT License
Author : hujingguang
Copyright MIT License
Author : hujingguang
@login_required(login_url='/')
def list_all_users(request):
users=User.objects.all()
for u in users:
if u.last_login:
u.last_login=datetime.strftime(u.last_login,'%Y-%m-%d %H:%M:%S')
else:
u.last_login=''
if u.date_joined:
u.date_joined=datetime.strftime(u.date_joined,'%Y-%m-%d %H:%M:%S')
else:
u.date_joined=''
return render_to_response('user_list.html',RequestContext(request,{'users':users}))
3
View Complete Implementation : test_views.py
Copyright MIT License
Author : wise-team
Copyright MIT License
Author : wise-team
def setUp(self):
initial_data.load()
for user in User.objects.all():
profile = Profile.objects.create(user=user)
profile.save()
build_1()
3
View Complete Implementation : test_basic.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
@override_settings(AUTH_USER_MODEL='auth.CustomUser')
def test_swappable_user(self):
"The current user model can be swapped out for another"
self.astertEqual(get_user_model(), CustomUser)
with self.astertRaises(AttributeError):
User.objects.all()
3
View Complete Implementation : permission_backend.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
Copyright GNU Affero General Public License v3.0
Author : archesproject
def get_users_for_object(perm, obj):
"""
returns a list of user objects that have the given permission on the given object
Arguments:
perm -- the permssion string eg: "read_nodegroup"
obj -- the model instance to check
"""
ret = []
for user in User.objects.all():
if user.has_perm(perm, obj):
ret.append(user)
return ret
3
View Complete Implementation : test_urlparser.py
Copyright MIT License
Author : Arello-Mobile
Copyright MIT License
Author : Arello-Mobile
def test_exclude_router_api_root(self):
clast MyViewSet(ModelViewSet):
serializer_clast = CommentSerializer
queryset = User.objects.all()
model = User
router = DefaultRouter()
router.register('test', MyViewSet, base_name='test_base_name')
urls_created = len(router.urls)
apis = self.urlparser.get_apis(router.urls)
self.astertEqual(4, urls_created - len(apis))
3
View Complete Implementation : views.py
Copyright MIT License
Author : CodeForPhilly
Copyright MIT License
Author : CodeForPhilly
def get_queryset(self):
username = self.request.query_params.get('username', None)
first_name = self.request.query_params.get('first_name', None)
last_name = self.request.query_params.get('last_name', None)
groups = self.request.query_params.get('groups', None)
pk = self.request.query_params.get('pk', None)
queryset = User.objects.all()
if username is not None:
queryset = queryset.filter(username__iexact=username)
if first_name is not None:
queryset = queryset.filter(first_name__iexact=first_name)
if last_name is not None:
queryset = queryset.filter(last_name__iexact=last_name)
if pk is not None:
queryset = queryset.filter(id=pk)
if groups is not None:
queryset = queryset.filter(role__role_value__icontains=groups)
return queryset
3
View Complete Implementation : 0006_auto_20190126_2143.py
Copyright MIT License
Author : hmlON
Copyright MIT License
Author : hmlON
def combine_names(apps, schema_editor):
from django.contrib.auth.models import User
for user in User.objects.all():
if user.social_auth.count() > 1:
user.social_auth.filter(provider='deezer').delete()
user.integration_set.filter(identifier='deezer').delete()
3
View Complete Implementation : test_views.py
Copyright MIT License
Author : wise-team
Copyright MIT License
Author : wise-team
def setUp(self):
initial_data.load()
for user in User.objects.all():
profile = Profile.objects.create(user=user)
profile.save()
settings.RESTRICT_PACKAGE_EDITORS = False
settings.RESTRICT_GRID_EDITORS = True
0
View Complete Implementation : test_urlparser.py
Copyright MIT License
Author : Arello-Mobile
Copyright MIT License
Author : Arello-Mobile
def test_format_api_patterns_url_import_with_routers(self):
clast MockApiViewSet(ModelViewSet):
serializer_clast = CommentSerializer
model = User
queryset = User.objects.all()
clast AnotherMockApiViewSet(ModelViewSet):
serializer_clast = CommentSerializer
model = User
queryset = User.objects.all()
router = DefaultRouter()
router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')
urls_app = patterns('', url(r'^', include(router.urls)))
urls = patterns(
'',
url(r'api/', include(urls_app)),
url(r'test/', include(urls_app))
)
apis = self.urlparser.get_apis(urls)
self.astertEqual(
4, sum(api['path'].find('api') != -1 for api in apis))
self.astertEqual(
4, sum(api['path'].find('test') != -1 for api in apis))
0
View Complete Implementation : models.py
Copyright MIT License
Author : ArnaudLevaufre
Copyright MIT License
Author : ArnaudLevaufre
@staticmethod
def notify_all(movie):
with transaction.atomic():
for user in User.objects.all():
NewMovieNotification.objects.create(movie=movie, user=user)
0
View Complete Implementation : test_user_profile.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
def setup(self):
self.client = Client()
self.astertEqual(len(User.objects.all()), 0)
0
View Complete Implementation : views.py
Copyright MIT License
Author : csev
Copyright MIT License
Author : csev
def listusers(request) :
ulist = User.objects.all()
ctx = { 'ulist' : ulist}
return render(request, 'usermodel/list.html', ctx)
0
View Complete Implementation : cleansedb.py
Copyright MIT License
Author : cyanfish
Copyright MIT License
Author : cyanfish
def handle(self, *args, **options):
Session.objects.all().delete()
for u in User.objects.all():
u.set_pastword("09876default1234")
u.email = "email-{}@example.com".format(u.id)
u.is_staff = False
u.last_login = None
u.date_joined = timezone.now()
u.save()
u.user_permissions.all().delete()
Group.objects.all().delete()
for p in Player.objects.all():
p.email = "email-{}@example.com".format(p.id)
p.slack_user_id = ''
p.timezone_offset = None
p.save()
for t in Team.objects.all():
t.slack_channel = ''
t.save()
Registration.objects.filter(status='rejected').delete()
Registration.objects.filter(status='pending').delete()
for r in Registration.objects.all():
r.email = "email-{}@example.com".format(r.id)
r.status = 'approved'
r.validation_ok = True
r.validation_warning = False
r.friends = ''
r.avoid = ''
r.slack_username = ''
r.save()
LeagueModerator.objects.all().delete()
Comment.objects.all().delete()
FcmSub.objects.all().delete()
GameNomination.objects.all().delete()
ApiKey.objects.all().delete()
PrivateUrlAuth.objects.all().delete()
LoginToken.objects.all().delete()
OauthToken.objects.all().delete()
# TODO: could probably selectively delete these, but meh.
SeasonDocameent.objects.all().delete()
LeagueDocameent.objects.all().delete()
Docameent.objects.all().delete()
PlayerNotificationSetting.objects.all().delete()
ModRequest.objects.all().delete()
LeagueChannel.objects.all().delete()
Revision.objects.all().delete()
ImpersonationLog.objects.all().delete()
ScheduledNotification.objects.all().delete()
PlayerPresence.objects.all().delete()
PlayerWarning.objects.all().delete()
0
View Complete Implementation : views.py
Copyright MIT License
Author : doccano
Copyright MIT License
Author : doccano
def get(self, request, *args, **kwargs):
queryset = User.objects.all()
serialized_data = UserSerializer(queryset, many=True).data
return Response(serialized_data)
0
View Complete Implementation : fetch_latest_releases.py
Copyright MIT License
Author : hmlON
Copyright MIT License
Author : hmlON
def handle(self, *args, **options):
users = User.objects.all()
for user in users:
self.stdout.write(self.style.SUCCESS(f'starting fetching for {user.email}'))
integration = None
if user.integration_set.filter(identifier='spotify').exists():
integration = user.integration_set.get(identifier='spotify')
SpotifyFetcher(user.id).fetch()
elif user.integration_set.filter(identifier='deezer').exists():
integration = user.integration_set.get(identifier='deezer')
DeezerFetcher(user.id).fetch()
if not integration:
continue
self.stdout.write(self.style.SUCCESS(f'finished fetching for {user.email}'))
if user.notification_set.filter(channel='email', enabled=True).exists():
notification = user.notification_set.get(channel='email')
new_since = notification.last_sent_at
# new_since = datetime.date.today() - datetime.timedelta(days=7)
new_releases = Release.objects.filter(
artist__integration_id=integration.id,
date__gte=new_since,
created_at__gte=new_since,
).order_by('-date', '-created_at')
# send an email
if new_releases.exists():
self.stdout.write(self.style.SUCCESS(f'sending an email for {user.email} '))
releases_text = [f'{release.date}: {release.artist.name} - {release.satle}' for release in new_releases]
releases_html = [f'{release.date}: {release.artist.name} - <a href="{release.integration_url}">{release.satle}</a>' for release in new_releases]
intro_text = 'Here are latest music releases that you have not seen before:'
outro_text = 'If you’d like to stop receiving these notifications, please visit the settings page.'
text_content = '\n'.join([intro_text] + releases_text + ['\n', '--', outro_text])
html_content = '<br>'.join([intro_text] + releases_html + ['\n', '--', outro_text])
to = notification.channel_id or user.email
send_mail(
f'New music releases since {new_since.date()}',
text_content,
'"MuN: latest releases" <[email protected]>',
[to],
html_message=html_content,
fail_silently=False,
)
notification.last_sent_at = datetime.datetime.now()
notification.save()
else:
self.stdout.write(self.style.SUCCESS(f'no new releases {user.email}'))
# send a telegram message
if user.notification_set.filter(channel='telegram', enabled=True).exists():
notification = user.notification_set.get(channel='telegram')
new_since = notification.last_sent_at
# new_since = datetime.date.today() - datetime.timedelta(days=7)
new_releases = Release.objects.filter(
artist__integration_id=integration.id,
date__gte=new_since,
created_at__gte=new_since,
).order_by('-date', '-created_at')
if new_releases.exists():
self.stdout.write(self.style.SUCCESS(f'sending a telegram message for {notification.channel_id} '))
releases_text = [
f'{release.date}: {release.artist.name} - [{release.satle}]({release.integration_url})'
for release in new_releases
]
intro_text = 'Here are latest music releases that you have not seen before:'
text = '\n'.join([intro_text] + releases_text)
bot_key = os.environ.get('TELEGRAM_API_KEY')
chat_id = notification.channel_id
send_message_url = f'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={chat_id}&text={text}&parse_mode=markdown'
requests.post(send_message_url)
# update last sent at
notification.last_sent_at = datetime.datetime.now()
notification.save()
else:
self.stdout.write(self.style.SUCCESS(f'no new releases {notification.channel_id}'))
0
View Complete Implementation : test_queryset.py
Copyright MIT License
Author : ivelum
Copyright MIT License
Author : ivelum
def test_empty_datetime(self):
qs = apply_search(User.objects.all(), 'last_login = None')
where_clause = str(qs.query).split('WHERE')[1].strip()
self.astertEqual('"auth_user"."last_login" IS NULL', where_clause)
0
View Complete Implementation : wagtailstreamforms_fields.py
Copyright MIT License
Author : labd
Copyright MIT License
Author : labd
@staticmethod
def get_queryset():
return User.objects.all()
0
View Complete Implementation : views.py
Copyright MIT License
Author : MicroPyramid
Copyright MIT License
Author : MicroPyramid
def users(request):
users = User.objects.all()
return render(request, 'users.html', {'users': users})
0
View Complete Implementation : update_balances.py
Copyright GNU General Public License v3.0
Author : msantl
Copyright GNU General Public License v3.0
Author : msantl
def handle(self, *args, **options):
# We only want to do this every other hour
if datetime.datetime.now().hour % 2 == 0:
return
users = User.objects.all()
market = Coinmarket()
currencies = Currency.objects.all()
fiats = Fiat.objects.all()
# update rates
for fiat in fiats:
rates = market.getRates(fiat.name)
for currency in currencies:
if currency.name in rates:
rate, _ = Rates.objects.get_or_create(
currency=currency.name, fiat=fiat.name)
rate.rate = rates[currency.name]
rate.save()
for user in users:
self.stdout.write("Refreshing balances for %s" % (user.email))
exchange_accounts = ExchangeAccount.objects.filter(user=user)
has_errors, errors = update_exchange_balances(exchange_accounts)
if has_errors:
for error in errors:
self.stderr.write("%s %s" % (user.email, error))
update_address_input_balances(user)
self.update_time_series(user)
0
View Complete Implementation : tasks.py
Copyright GNU Affero General Public License v3.0
Author : MTG
Copyright GNU Affero General Public License v3.0
Author : MTG
@shared_task
def compute_annotators_ranking(store_key, dataset_id, N=10):
logger.info('Start computing data for {0}'.format(store_key))
try:
dataset = Dataset.objects.get(id=dataset_id)
reference_date = timezone.now() - datetime.timedelta(days=7)
current_day_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
ranking = list()
ranking_last_week = list()
ranking_today = list()
ranking_agreement_today = list()
for user in User.objects.all():
# all time
n_annotations = CandidateAnnotation.objects.filter(created_by=user, sound_dataset__dataset=dataset, type='MA').count()
n_votes = Vote.objects.filter(created_by=user, candidate_annotation__sound_dataset__dataset=dataset).count()
ranking.append(
(user.username, n_annotations + n_votes)
)
# last week
n_annotations_last_week = CandidateAnnotation.objects.filter(
created_at__gt=reference_date, created_by=user, sound_dataset__dataset=dataset, type='MA').count()
n_votes_last_week = Vote.objects.filter(
created_at__gt=reference_date, created_by=user, candidate_annotation__sound_dataset__dataset=dataset).count()
ranking_last_week.append(
(user.username, n_annotations_last_week + n_votes_last_week)
)
# today
agreement_score = 0
n_annotations_today = CandidateAnnotation.objects.filter(
created_at__gt=current_day_date, created_by=user, sound_dataset__dataset=dataset, type='MA').count()
n_votes_today = Vote.objects.filter(
created_at__gt=current_day_date, created_by=user, candidate_annotation__sound_dataset__dataset=dataset).count()
ranking_today.append(
(user.username, n_annotations_today + n_votes_today)
)
# agreement score today
votes = Vote.objects.filter(created_by=user,
candidate_annotation__sound_dataset__dataset=dataset,
created_at__gt=current_day_date)
for vote in votes:
all_vote_values = [v.vote for v in vote.candidate_annotation.votes.all()]
if all_vote_values.count(vote.vote) > 1:
agreement_score += 1
elif len(all_vote_values) > 1:
past
else:
agreement_score += 0.5
try:
ranking_agreement_today.append(
(user.username, agreement_score/float(n_votes_today))
)
except ZeroDivisionError:
ranking_agreement_today.append(
(user.username, 0)
)
ranking = sorted(ranking, key=lambda x: x[1], reverse=True) # Sort by number of annotations
ranking_last_week = sorted(ranking_last_week, key=lambda x: x[1], reverse=True)
ranking_today = sorted(ranking_today, key=lambda x: x[1], reverse=True)
ranking_agreement_today = sorted(ranking_agreement_today, key=lambda x: x[1], reverse=True)
store.set(store_key, {'ranking': ranking[:N], 'ranking_last_week': ranking_last_week[:N],
'ranking_today': ranking_today, 'ranking_agreement_today': ranking_agreement_today})
logger.info('Finished computing data for {0}'.format(store_key))
except Dataset.DoesNotExist:
past
except User.DoesNotExist:
past
0
View Complete Implementation : tasks.py
Copyright MIT License
Author : OnGridSystems
Copyright MIT License
Author : OnGridSystems
@periodic_task(run_every=crontab(minute='*/1'))
def calculate_holdings_history():
date = datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')
users = User.objects.all()
for user in users:
wallets = UserWallet.objects.filter(user=user)
if len(wallets) > 0:
for wallet in wallets:
holdings = UserHoldings()
holdings.user = user
holdings.type = 'Wallet@' + wallet.wallet.name + '(' + str(wallet.pk) + ')'
holdings.total_btc = wallet.total_btc
holdings.total_usd = wallet.total_usd
holdings.date_time = date
holdings.save()
exchanges = UserExchange.objects.filter(user=user)
if len(exchanges) > 0:
for exchange in exchanges:
holdings = UserHoldings()
holdings.user = user
holdings.type = 'Exchange@' + exchange.exchange.name + '(' + str(exchange.pk) + ')'
holdings.total_btc = exchange.total_btc
holdings.total_usd = exchange.total_usd
holdings.date_time = date
holdings.save()
return True
0
View Complete Implementation : django_app.py
Copyright MIT License
Author : scoutapp
Copyright MIT License
Author : scoutapp
@SimpleLazyObject
def drf_router():
"""
DRF Router as a lazy object because it needs to import User model which
can't be done until after django.setup()
"""
from django.contrib.auth.models import User
from rest_framework import routers
from rest_framework import serializers
from rest_framework import viewsets
clast UserSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
username = serializers.CharField(max_length=200)
clast UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_clast = UserSerializer
router = routers.SimpleRouter()
router.register(r"users", UserViewSet)
return router
0
View Complete Implementation : django_app.py
Copyright MIT License
Author : scoutapp
Copyright MIT License
Author : scoutapp
@SimpleLazyObject
def tastypie_api():
"""
Tastypie API as a lazy object because it needs to import User model which
can't be done until after django.setup()
"""
from django.contrib.auth.models import User
try:
from tastypie.api import Api as TastypieApi
from tastypie.resources import ModelResource as TastypieModelResource
except ImportError:
return None
clast UserResource(TastypieModelResource):
clast Meta:
queryset = User.objects.all()
allowed_methods = ["get"]
api = TastypieApi(api_name="v1")
api.register(UserResource())
return api