class TeamModelTestCase(TestCase): def setUp(self): self.tournament = Tournament() self.tournament.save() self.group = Group(letter='A') self.group.tournament_id = self.tournament.id self.group.save() self.team = Team(name='Brazil') self.team.group_id = self.group.id def test_model_can_create_team(self): old_count = Team.objects.count() self.team.save() new_count = Team.objects.count() created_team = Team.objects.last() self.assertNotEqual(old_count, new_count) self.assertEquals(self.team.name, created_team.name) self.assertEquals(self.team.points, created_team.points) self.assertEquals(self.team.goals, created_team.goals) self.assertEquals(self.team.position, created_team.position) self.assertEquals(self.team.group.letter, self.group.letter) self.assertEquals(self.team, self.group.teams.get()) def test_model_cannot_create_team_without_name(self): team_without_name = Team() with self.assertRaises(IntegrityError): team_without_name.save() def test_model_cannot_create_team_without_group(self): team_without_group = Team(name='Japan') with self.assertRaises(IntegrityError): team_without_group.save()
def groups(request): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] if request.method == 'POST': form = groupAddForm(request.POST) if form.is_valid(): group = form.cleaned_data new_group = Group(name=group['name']) new_group.save() return HttpResponseRedirect(request.get_full_path()) else: for msg_err in form.errors.values(): error_messages.append(msg_err.as_text()) groups = Group.objects.all().order_by('name') groups_inst = [] for group in groups: groups_inst.append( (group, Instance.objects.filter(group=group).order_by('name'))) return render(request, 'groups.html', locals())
def groups(request): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] if request.method == 'POST': form = groupAddForm(request.POST) if form.is_valid(): group = form.cleaned_data new_group = Group(name=group['name']) new_group.save() return HttpResponseRedirect(request.get_full_path()) else: for msg_err in form.errors.values(): error_messages.append(msg_err.as_text()) groups = Group.objects.all().order_by('name') groups_inst = [] for group in groups: groups_inst.append((group, Instance.objects.filter(group=group).order_by('name'))) return render(request, 'groups.html', locals())
def form_valid(self, form): group = Group(name=form.cleaned_data['name'], creator_id=self.request.user.id) group.save() GroupUser(group_id=group.id, user_id=self.request.user.id, confirmed=True, is_creator=True).save() for user in form.cleaned_data['users']: GroupUser(group_id=group.id, user_id=user.id, confirmed=False, is_creator=False).save() return HttpResponseRedirect(reverse('groups:index'))
def group_create(request, assignment_id): assignment = get_object_or_404(Assignment, id=assignment_id) # students = assignment.discipline.group.profiles.filter(student=True) students = [] for profile in assignment.discipline.group.profiles.all(): if profile.is_student(): students.append(profile) if request.method == 'POST': form = GroupForm(students, request.POST) if form.is_valid(): g = Group() g.name = form.cleaned_data['name'] g.save() for selected_student in form.cleaned_data['students']: g.profiles.add(Profile.objects.get(pk=selected_student)) g.profiles.add(assignment.discipline.teacher.profile) assignment.group.add(g) return HttpResponseRedirect(reverse("educational:assignment_detail", kwargs={'pk': assignment.pk})) else: form = GroupForm(students) return render(request, 'educational/teacher/group_create.html', {'form': form})
def add_group(request): # print("checkbox input field") # print(request.POST.getlist('members')) try: g = Group( group_name=request.POST['group_name'], topic=request.POST['topic'], create_date=timezone.now(), creator_username=request.user.username ) g.save() groupMembers = request.POST.getlist('members') for u in groupMembers: # print "user:"******"!", }) else: g.save() return HttpResponseRedirect(reverse('forum:index')) return render()
def setUp(self): self.tournament = Tournament() self.tournament.save() self.group = Group(letter='A') self.group.tournament_id = self.tournament.id self.group.save() self.team = Team(name='Brazil') self.team.group_id = self.group.id
def search(request): num_pages = 0 limit = None nonvouched_only = False picture_only = False people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] vouched = False if form.cleaned_data['nonvouched_only'] else None profilepic = True if form.cleaned_data['picture_only'] else None page = request.GET.get('page', 1) curated_groups = Group.get_curated() # If nothing has been entered don't load any searches. if not (not query and vouched is None and profilepic is None): profiles = UserProfile.search(query, vouched=vouched, photo=profilepic) groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if len(profiles) == 1 and not groups: return redirect(reverse('profile', args=[people[0].user.username])) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, nonvouched_only=nonvouched_only, picture_only=picture_only, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def setUp(self): user_obj = User(email='*****@*****.**') user_obj.set_password("randPassword") user_obj.save() group = Group() group.save() student_groups = StudentGroups(user=user_obj) student_groups.groups_list.add(group) student_groups.save()
class MatchModelTestCase(TestCase): def setUp(self): self.phase = Tournament.FIRST_PHASE self.group_letter = 'A' self.team_a_name = 'Brazil' self.team_b_name = 'Germany' self.tournament = Tournament(phase=self.phase) self.tournament.save() self.group = Group(letter=self.group_letter) self.group.tournament_id = self.tournament.id self.group.save() self.team_a_goals = random.randint(0, 10) self.team_b_goals = random.randint(0, 10) self.team_a = Team(name=self.team_a_name) self.team_b = Team(name=self.team_b_name) self.team_a.group_id = self.group.id self.team_b.group_id = self.group.id self.team_a.save() self.team_b.save() def test_model_can_create_match(self): old_count = Match.objects.count() match = Match(away_team=self.team_a, home_team=self.team_b, away_team_goals=self.team_a_goals, home_team_goals=self.team_b_goals, tournament=self.tournament, phase=self.tournament.phase) match.save() new_count = Match.objects.count() created_match = Match.objects.last() self.assertNotEquals(old_count, new_count) self.assertEquals(created_match.phase, self.tournament.phase) self.assertEquals(created_match.away_team.id, self.team_a.id) self.assertEquals(created_match.away_team_goals, self.team_a_goals) self.assertEquals(created_match.home_team.id, self.team_b.id) self.assertEquals(created_match.home_team_goals, self.team_b_goals) self.assertFalse(created_match.played) self.assertIsNone(created_match.winner) def test_model_cannot_create_match_without_teams(self): match_without_teams = Match() with self.assertRaises(IntegrityError): match_without_teams.save() def test_model_can_create_match_without_input_goals(self): expected_amount_goals = 0 match_without_goals = Match(away_team=self.team_a, home_team=self.team_b, tournament=self.tournament, phase=self.tournament.phase) match_without_goals.save() created_match = Match.objects.last() self.assertEquals(created_match.away_team_goals, expected_amount_goals) self.assertEquals(created_match.away_team_goals, expected_amount_goals) self.assertEquals(created_match.phase, self.phase)
def search(request): num_pages = 0 limit = None nonvouched_only = False picture_only = False people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] vouched = False if form.cleaned_data['nonvouched_only'] else None profilepic = True if form.cleaned_data['picture_only'] else None page = request.GET.get('page', 1) curated_groups = Group.get_curated() # If nothing has been entered don't load any searches. if not (not query and vouched is None and profilepic is None): profiles = UserProfile.search(query, vouched=vouched, photo=profilepic) groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if len(profiles) == 1 and not groups: return redirect( reverse('profile', args=[people[0].user.username])) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, nonvouched_only=nonvouched_only, picture_only=picture_only, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def setUp(self): user_obj = User(email='*****@*****.**', is_lecture=True) user_obj.set_password("randPassword") user_obj.save() group = Group() group.save() lecture_groups = LectureGroups(user=user_obj) lecture_groups.groups_list.add(group) lecture_groups.save()
def test_group_submission_view(self): """ test if group submission can be viewed by group member and non group member """ now = datetime.datetime.now() _, course = create_offering() a1 = NumericActivity(name="Assignment 1", short_name="A1", status="RLS", offering=course, position=2, max_grade=15, due_date=now, group=True) a1.save() a2 = NumericActivity(name="Assignment 2", short_name="A2", status="RLS", offering=course, position=1, max_grade=15, due_date=now, group=True) a2.save() p = Person.objects.get(userid="ggbaker") member = Member(person=p, offering=course, role="INST", career="NONS", added_reason="UNK") member.save() c1 = URL.Component(activity=a1, title="URL Link", position=8) c1.save() c2 = Archive.Component(activity=a1, title="Archive File", position=1, max_size=100000) c2.save() c3 = Code.Component(activity=a1, title="Code File", position=3, max_size=2000, allowed=".py") c3.save() userid1 = "0aaa0" userid2 = "0aaa1" userid3 = "0aaa2" for u in [userid1, userid2,userid3]: p = Person.objects.get(userid=u) m = Member(person=p, offering=course, role="STUD", credits=3, career="UGRD", added_reason="UNK") m.save() m = Member.objects.get(person__userid=userid1, offering=course) g = Group(name="Test Group", manager=m, courseoffering=course) g.save() gm = GroupMember(group=g, student=m, confirmed=True, activity=a1) gm.save() gm = GroupMember(group=g, student=m, confirmed=True, activity=a2) gm.save() m = Member.objects.get(person__userid=userid2, offering=course) gm = GroupMember(group=g, student=m, confirmed=True, activity=a1) gm.save() gm = GroupMember(group=g, student=m, confirmed=True, activity=a2) gm.save() m = Member.objects.get(person__userid=userid3, offering=course) gm = GroupMember(group=g, student=m, confirmed=True, activity=a2) gm.save() client = Client() # login as "0aaa0", member of group : test_group for assignment1 and assgnment2 client.login_user("0aaa0") #submission page for assignment 1 url = reverse('submission.views.show_components', kwargs={'course_slug': course.slug,'activity_slug':a1.slug}) response = basic_page_tests(self, client, url) self.assertContains(response, "This is a group submission. You will submit on behalf of the group Test Group.") self.assertContains(response, "You haven't made a submission for this component.")
def setUp(self): self.club = Club(name="NTNUI") self.club.save() self.group = Group(name="NTNUI Fotball", club=self.club) self.group.save() self.user = User.objects.create_superuser("testuser", email="*****@*****.**", password="******") self.user.save() self.interest = Interest(session_id="c00k13M0n5t3r", group=self.group) self.interest.save() self.factory = APIRequestFactory() self.interests = Interest.objects.all()
def groupcreate(request): try: if Group.objects.filter(name=request.POST['groupName']): return HttpResponse('小组已存在 ! ') else: policy = qiniu.rs.PutPolicy('mzgroup') uptoken = policy.token() if 'groupImg' in request.FILES: tj=time.time() image=request.FILES['groupImg'] suffix=image.name.split('.')[-1] image=Image.open(image) coordinate=request.POST['coordinate'].split('*') region = (int(round(float(coordinate[0]))+1),int(coordinate[1]),int(coordinate[2]),int(coordinate[3])) cropImg = image.crop(region) cropImg.save(r"/home/tron/Maizhi/templates/picture/group/image/"+str(tj)+'.'+suffix) #dirs ='templates/picture/group/image/'+str(tj) #content = image.read() #if os.path.isfile(dirs): # os.remove(dirs) #fp=open(dirs, 'wb') #fp.write(content) #fp.flush() #fp.close() domain="http://mzgroup.qiniudn.com" ret=qiniu.io.put_file(uptoken,str(tj),r"/home/tron/Maizhi/templates/picture/group/image/"+str(tj)+'.'+suffix) #if ret: # os.remove(dirs) else: filename=None g=Group(name=request.POST['groupName'],introduce=request.POST['groupIntro'],img=str(tj),domain=domain,user_id=request.session['id']) g.save() return render(request,'groups/success.html',{'g':g.id}) except: m=Message.objects.filter(to=request.session['id']).order_by('-time')[0:5] mess=[] for k in m: each=[] name=Info.objects.get(user_id=k.from_id).user_name content=k.content each.append(name) each.append(content) mess.append(each) havent=0 for n in m: if n.status==1: havent+=1 info=Info.objects.get(user_id=request.session['id']) return render(request,'groups/groupCreate.html',{'info':info,'message':mess,'havent':havent})
def post(self, request, *args, **kwargs): data = request.data #create a new group given the name, description, and image serializer = GroupSerializer(data=data) if (serializer.is_valid(raise_exception=True)): group_obj = Group(name=data.get('name'), description=data.get('description'), image=data.get('image')) group_obj.save() #associate the group with the owner and members through Membership owner = request.user if (not Membership.objects.filter(user=owner, group=group_obj).exists()): own_mem_obj = Membership(user=owner, group=group_obj, owner=True) own_mem_obj.save() members = data.get('members', '') members = [item.strip() for item in members.strip().split(',')] for member in members: try: user_obj = User.objects.get(email=member) except User.DoesNotExists: pass if (not Membership.objects.filter(user=user_obj, group=group_obj).exists()): mem_obj = Membership(user=user_obj, group=group_obj, owner=False) mem_obj.save() #notify the group msg_obj = BuddyMessage(user=user_obj, group=group_obj, message=''.join((user_obj.buddycode, ' joined the group')), message_type=settings.MSG_TYPE_JOIN) msg_obj.save() #create an activity for the owner if (not CreateGroup.objects.filter(user=owner, group=group_obj).exists()): activity_obj = CreateGroup(owner=owner, group=group_obj, longitude=owner.longitude, latitude=owner.latitude) activity_obj.save() return Response({"success": True}, status=HTTP_200_OK)
def home_page(request): # Home page get is searching for groups if request.method == 'POST': name = request.POST['group_name'] alias = request.POST['group_alias'] tags = request.POST['group_tags'] description = request.POST['group_description'] if verification(request, name, alias, tags, description): return verification(request, name, alias, tags, description) group = Group( name = name, alias = alias, tags = tags, description = description) try: group.full_clean() group.save() except ValidationError: error = "Nao pode-se adicionar um grupo vazio!" return render(request, 'home.html', {'group_description_error_message': error}) #return render(request, 'home.html', { # 'group_success': True, # 'open_popup': True, # 'group_name': group.name, # 'group_tags': group.tags, # 'group_alias': group.alias, # 'group_description': group.description # }) return render(request, 'home.html', { 'group_success': True, 'open_popup': True, 'group_name': name }) if request.method == 'GET': search_tags = request.GET.get('search_group', '') if search_tags != '': found_groups = search_groups(search_tags) return render(request, 'home.html', { 'groups': found_groups }) return render(request, 'home.html', {'form': GroupForm()})
def landingpage(request): user_ids = [s.user_id for s in SocialUser.all()] return render( request, 'landingpage.html', { 'video_count': len(list(Video.all())), 'group_count': len(list(Group.all())), 'socialuser_count': len(set(user_ids)), 'socialuser_all_count': len(user_ids), 'overall_suggestions_count': statistics.overall_suggestions_count(), 'overall_suggestions_user_count': statistics.overall_suggestions_user_count(), 'suggestions_user_count': statistics.suggestions_user_count(), 'overall_watch_count': statistics.overall_watch_count(), 'overall_watch_user_count': statistics.overall_watch_user_count(), 'watch_user_count': statistics.watch_user_count(), 'overall_dismiss_count': statistics.overall_dismiss_count(), 'overall_dismiss_user_count': statistics.overall_dismiss_user_count(), 'dismiss_user_count': statistics.dismiss_user_count(), 'user_watches': statistics.user_watches(), })
def delete(self, request, group_id=None): group = Group.safe_get(group_id) if not group: return HTTPResponse({"No such group found !"}) group.delete() response = {} return HTTPResponse(response)
def retrieve(self, request, group_id=None): group = Group.safe_get(group_id) if not group: return HTTPResponse({"No such group found !"}) response = { "id": str(group.id), "title": group.title, "level_id": str(group.level_id.id) if group.level_id else "", "level_no": group.level_id.level_no, "level_title": group.level_id.title, "admin_id": str(group.admin_id.id) if group.admin_id else "", "admin_name": group.admin_id.get_full_name() if group.admin_id else '', "parent_group_id": str(group.parent_group_id.id) if group.parent_group_id else "", "parent_group_name": group.parent_group_id.title if group.parent_group_id else "" } return HTTPResponse(response)
def groups(request): global newsgroup try: username = request.POST['submitted_username'] password = request.POST['submitted_password'] newsgroup = NewsGroup('news.cs.illinois.edu', username, password) except(Exception): return redirect('/') else: groups = newsgroup.getGroups() db_groups = Group.objects.all() for group in groups: if not db_groups.filter(name=group[0]): g = Group(name=group[0], description = group[1]) g.save() return render_to_response('groups/groups.html', {'group_list' : db_groups})
def get_users_groups_slots(user): groups = Group.get_is_member_list(user) events = None slots = None for group in groups: if (events == None): events = Event.objects.filter(parentGroup=group) else: groups_events = Event.objects.filter(parentGroup=group) events = events | groups_events if (slots == None): slots = Slot.objects.filter(parentGroup=group) else: groups_slots = Slot.objects.filter(parentGroup=group) slots = slots | groups_slots if events == None: return None for event in events: if (slots == None): slots = Slot.objects.filter(parentEvent=event) else: events_slots = Slot.objects.filter(parentEvent=event) slots = slots | events_slots if (slots == None): return slots return slots.order_by( 'start' ) # Slot.objects.filter(Q(parentEvent.parentGroup.get_is_member(user))).objects.order_by('start')
def detail(request, id): context = Group.verification_of_rights(request, id) if context['status']: group = get_object_or_404(Group, id=id) members = Membership.objects.filter(group=group, role__role__in=['admin', 'editor', 'subscribers']) \ .only('role') try: roles = Membership.objects.get(person=request.user.profile, group=id).role except Membership.DoesNotExist: roles = '' chat = Room.objects.get(group=group.id) context = { 'roles': roles, 'group': group, 'members': members, 'avatar': GroupAvatar.objects.get(group=group.id), 'chat': chat, 'user': request.user } else: return render_to_response('groups/error.html', context) return render_to_response('groups/detail.html', context)
def chat(request, group_id): group = Group.objects.get(id=group_id) if not Group.get_is_member(group, request.user): return HttpResponse( 'You don\'t have the right permissions to see this page. You must be a member to access this page.' ) chat_entries = Chat_Entry.objects.filter( parentGroup=group).order_by('datetime') if (request.method == 'POST'): form = NewChatEntryForm(request.POST, user=request.user, parentGroup=group) if form.is_valid(): chat = form.save(commit=False) chat.save() return redirect('/groups/' + str(group_id) + '/chat/') else: form = NewChatEntryForm(user=request.user, parentGroup=group) # Filter this by single slot events in the future return render(request, 'groups/chat.html', { 'entries': chat_entries, 'form': form })
def handle(self, *args, **options): Group.objects.all().delete() Student.objects.all().delete() Teacher.objects.all().delete() # Create 100 students wo group/teacher students = [Student.generate_student() for i in range(100)] print(len(students)) # Create 10 teachers wo group teachers = [Teacher.gen_teacher() for i in range(10)] print(len(teachers)) # Create 10 groups wo teacher and senior groups = [Group.gen_group() for i in range(10)] # Update students with random Group for student in students: student.groups = random.choice(groups) print(student.groups) student.save() # Add for Group senior FROM THE GROUP and curator - random teacher for group in groups: while group.senior is None: student = random.choice(students) if student.groups.id == group.id: group.senior = student else: print(f'student {student.groups} not in group {group.id}') group.curator = random.choice(teachers) group.save() print(group.get_info())
def _account_numbers_dict(account): start_of_this_year = datetime.date(month=1, day=1, year=datetime.date.today().year) total_donations = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).count() if not total_donations: total_donations = 0 total_donors = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Count('donor', distinct=True))["donor__count"] if not total_donors: total_donors = 0 total_donation_amount = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Sum('amount'))["amount__sum"] if not total_donation_amount: total_donation_amount = 0 average_donation = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Avg('amount'))["amount__avg"] if not average_donation: average_donation = 0 total_volunteer_hours = CompletedShift.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Sum('duration'))["duration__sum"] if not total_volunteer_hours: total_volunteer_hours = 0 total_people = Person.objects_by_account(account).count() total_orgs = Organization.objects_by_account(account).count() total_groups = Group.objects_by_account(account).count() total_tags = Tag.objects_by_account(account).count() total_taggeditems = TaggedItem.objects_by_account(account).count() recent_conversations = Conversation.objects_by_account(account).all()[:5] return locals()
def test_get_list_view(self): response = self.client.get(reverse('groups:list')) self.assertEqual(response.status_code, 200) self.assertIn('groups', response.context) groups = list(response.context['groups']) all_groups = Group.all() self.assertTrue(all(group in all_groups for group in groups))
def add(group_name): try: group = Group(name=group_name, user_id=g.auth['sub']) db.session.add(group) db.session.commit() except IntegrityError as e: raise AlreadyExistsError(group_name) return ('', HTTPStatus.NO_CONTENT)
def addgroup(request): if 'groupname' in request.POST: groupname = request.POST['groupname'] # Create the new group group = Group(name=groupname) group.save() # Add the current user to the group # Make sure to use user instead of id b/c not equal member = Member.objects.get(user=User.objects.get(id=request.user.id)) member.groups.add(group) return detail(request, group.id) else: # TODO: Add some sort of error here. Group name is empty. return index(request)
def save(self): if self.model is None: self.model = Group(name='', visible=True, key='') data = self.cleaned_data self.model.name=data['name'] self.model.visible=data['visible'] self.model.key=data.get('key') return self.model
def create_course_group(self, request, pk=None): course = self.get_object() group_name = request.data.get('name') group = Group(name=group_name, course=course) group.save() for student in group.students.all(): assign_perm('groups.view_group', student.user, group) # Assign view permission to students in group for assistant in group.course.assistant_set.all(): assign_perm('groups.view_group', assistant.user, group) assign_perm('groups.change_group', assistant.user, group) assign_perm('groups.change_group', group.course.professor.user, group) assign_perm('groups.delete_group', group.course.professor.user, group) assign_perm('groups.view_group', group.course.professor.user, group) return Response(GroupSerializer(group).data)
def create_sample_group_db(self, name, alias, tags, description): sample_group = Group() sample_group.name = name sample_group.alias = alias sample_group.tags = tags sample_group.description = description sample_group.save()
def create_group(name, email, url_root, owner): """ _name_ Name of group _email_ Email address for group (?) _url_root_ acSite _owner_ MCID of user/doctor that controls this group """ u = User() u.mcid = mcid_generator.next_mcid() u.email = email u.set_password(str(u.mcid)) u.first_name = name u.last_name = 'Group' u.rolehack = 'rls' u.acctype = 'GROUP' u.updatetime = 0 u.ccrlogupdatetime = 0 u.save() g = Group() g.grouptypeid = 0 g.name = name g.accid_id = u.mcid g.save() p = Practice() p.providergroupid = g p.practicename = name p.accid_id = u.mcid p.save() p.practiceRlsUrl = urljoin(url_root, 'acct/ws/R.php?pid=%d' % p.practiceid) p.save() g.parentid = p.practiceid g.save() ga = Groupadmin() ga.groupinstanceid = g.groupinstanceid ga.adminaccid = owner ga.save() add_to_group(g, owner) return g, p
def test_group_size_restriction(self): group = Group() group.group_letter = 'A' teams = [] for i in range(0,6): teams.append(make_phony_team()) group.save() group.teams = teams self.assertRaises(ValidationError, group.save) teams = [] for i in range(0,3): teams.append(make_phony_team()) group.teams = teams self.assertRaises(ValidationError, group.save) teams = [] for i in range(0,4): teams.append(make_phony_team()) group.teams = teams
def test_membership(self): membership = Membership() user = User.objects.create_user('Testy McTest', '*****@*****.**', 'testpassword') user.save() group = Group() group.name = "Test Group" group.save() membership.user = User.objects.get(id=user.id) membership.group = Group.objects.get(id=group.id) membership.is_admin = False membership.save() test_membership = Membership.objects.get(id=membership.id) self.assertEquals(test_membership, membership) self.assertEquals(test_membership.user, User.objects.get(id=user.id)) self.assertEquals(test_membership.group, Group.objects.get(id=group.id)) self.assertEquals(test_membership.is_admin, False) membership.delete() group.delete() user.delete()
def setUp(self): self.phase = Tournament.FIRST_PHASE self.group_letter = 'A' self.team_a_name = 'Brazil' self.team_b_name = 'Germany' self.tournament = Tournament(phase=self.phase) self.tournament.save() self.group = Group(letter=self.group_letter) self.group.tournament_id = self.tournament.id self.group.save() self.team_a_goals = random.randint(0, 10) self.team_b_goals = random.randint(0, 10) self.team_a = Team(name=self.team_a_name) self.team_b = Team(name=self.team_b_name) self.team_a.group_id = self.group.id self.team_b.group_id = self.group.id self.team_a.save() self.team_b.save()
def delete_group(request): group_id = request.POST['group_id'] if Group.is_group_admin(request, group_id): try: Group.objects.get(id=group_id).update(active=2) # TODO Проверить except Group.DoesNotExist: return HttpResponse('Error') return HttpResponse(str(200)) return HttpResponse('Недостаточно прав для редактирования')
def post(self, request): username = request.POST.get('username') name = request.POST.get('name') price = int(request.POST.get('price')) avl_times = int(request.POST.get('avl_times')) img = request.FILES.get('qrcode') user = request.user g = Group.create(user.id, username, name, price, avl_times, img) return g.get_info()
def home(request): if request.user.is_authenticated(): profile = request.user.get_profile() my_groups = profile.groups.exclude(steward=None).order_by('name') curated_groups = Group.get_curated() data = dict(groups=my_groups, curated_groups=curated_groups) return render(request, 'phonebook/home.html', data) else: return render(request, 'phonebook/home.html')
def handle(self, *args, **options): Group.objects.all().delete() Category.objects.all().delete() Choice.objects.all().delete() Question.objects.all().delete() #сбрасываем автоинкремент чтобы не ловить индекс категории from django.db import connection cursor = connection.cursor() sql = 'ALTER TABLE groups_group AUTO_INCREMENT=1;' cursor.execute(sql) sql = 'ALTER TABLE questions_category AUTO_INCREMENT=1;' cursor.execute(sql) for i in range(0, self.groups_pool_length): group = Group(name=self.groups_prefix + str(i + 1)) group.save() print 'Таблица групп наполнена' for i in range(0, self.categories_pool_length): category = Category(name=self.categories_prefix + str(i + 1)) category.save() print 'Таблица категорий наполнена' import random for i in range(0, self.questions_pool_length): a = random.randint(0, 20) b = random.randint(0, 20) answer = a + b question_text = '%s %s. Введите правильный ответ в выражении %s+%s' % ( self.questions_prefix, i, a, b) question = Question( category=Category.objects.all().order_by('?')[0], question=question_text, answer=str(answer)) question.save() for j in range(3): choice = Choice( question=question, choice_text=answer + (-1)**random.randint(0, 10) * random.randint(1, 3)) choice.save() print 'Таблицы вопросов и выборов наполнены'
def handle(self, **options): group_id = options['group_id'] if group_id: group_id = int(group_id) if not group_id: raise Exception("--group_id is required!") group_src = Group.objects.get(id=group_id) group_dst = Group() group_dst.__dict__ = copy.deepcopy(group_src.__dict__) group_dst.id = None group_dst.name += " copy" group_dst.save() for student_src in group_src.students.all(): print "Copy student {0}".format(student_src.get_full_name().encode("utf-8")) group_dst.students.add(student_src)
def search(request): if 'hood_name' in request.GET and request.GET["hood_name"]: search_term = request.GET.get("hood_name") searched_hoods = Group.search_by_name(search_term) message = f"{search_term}" return render(request, 'group_search.html', {"hoods": searched_hoods}) else: message = "You haven't searched for any term" return render(request, 'group_search.html')
def save(self, commit=True): inst = super(EventForm, self).save(commit=False) inst.creator = self.creator_user if self.new: att = Group.create_for_event(inst.currency) inst.attendees = att if commit: inst.save() return inst
def delete_subscribers(request): group_id = request.POST['group_id'] if Group.is_group_admin(request, group_id): try: users_object = Membership.objects.get(group_id=group_id, person=request.POST['user']) users_object.delete() except Membership.DoesNotExist: return HttpResponse('Error') return HttpResponse(str(200)) return HttpResponse('Недостаточно прав для редактирования')
def filterByGroup(request, group_id): group = Group.objects.get(id=group_id) if (request.user.is_authenticated() and group.get_is_member(request.user)): groups = Group.get_is_member_list(request.user) feed_entries = Feed_Entry.objects.filter(group=group).order_by('-datetime') #feed entries are sorted from most recent to least recent return render(request, 'feed/feed.html', {'feed_entries':feed_entries, 'groups':groups}) else: if (not(group.get_is_member(request.user))): return redirect('feed') else: return redirect('login')
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.pk: if not self.code: self.code = self.name[:15] group = Group(name=self.name) group.save() group.profiles.add(self.teacher.profile) group.save() self.group = group parent_group = Group(name=u'{0} - {1}'.format(self.name, _(u'Guardians'))) parent_group.save() parent_group.profiles.add(self.teacher.profile) parent_group.save() self.parent_group = parent_group self.group.name = self.name self.group.save() self.parent_group.name = u'{0} - {1}'.format(self.name, _(u'Guardians')) self.parent_group.save() super(Discipline, self).save()
def test_post(self): post = Post() user = User.objects.create_user('Testy McTest', '*****@*****.**', 'testpassword') user.save() group = Group() group.name = "Test Group" group.save() membership = Membership() membership.user = User.objects.get(id = user.id) membership.group = Group.objects.get(id = group.id) membership.save() post.author = Membership.objects.get(id = membership.id) post.message = "Testing321" post.save() test_post = Post.objects.get(id = post.id) self.assertEquals(test_post, post) self.assertEquals(test_post.author, Membership.objects.get(id = membership.id)) self.assertEquals(test_post.message, "Testing321") post.delete() membership.delete() group.delete() user.delete()
def test_membership(self): membership = Membership() user = User.objects.create_user("Testy McTest", "*****@*****.**", "testpassword") user.save() group = Group() group.name = "Test Group" group.save() membership.user = User.objects.get(id=user.id) membership.group = Group.objects.get(id=group.id) membership.is_admin = False membership.save() test_membership = Membership.objects.get(id=membership.id) self.assertEquals(test_membership, membership) self.assertEquals(test_membership.user, User.objects.get(id=user.id)) self.assertEquals(test_membership.group, Group.objects.get(id=group.id)) self.assertEquals(test_membership.is_admin, False) membership.delete() group.delete() user.delete()
def create_group(request): kwargs = simplejson.loads(request.raw_post_data) gr_name = kwargs['name'] is_pub = kwargs['is_public'] reqs_allowed = kwargs['requests_allowed'] existing_group = Group.objects.filter(name=gr_name) if existing_group.count() == 0: try: gr = Group(name=gr_name, is_public=is_pub, requests_allowed=reqs_allowed) gr.save() mship = Membership(user=request.user, group=gr, is_owner=True, is_admin=True) mship.save() response_dict = {'error': None, 'result': 'Group created!'} except: response_dict = unkown_error_dict() else: response_dict = {'error': 'Group name already exists!', 'result': None} return json_http_response(response_dict)
def test_only_displays_GET_on_search(self): first_group = Group() first_group.name = 'Teh empty tag' first_group.alias = 'tehalias' first_group.tags = '' first_group.description = 'Teh empty description' first_group.save() request = HttpRequest() request.method = 'GET' response = home_page(request) self.assertNotIn('Teh empty tag', response.content.decode())
def make_phony_group(): team1 = make_phony_team() team2 = make_phony_team() team3 = make_phony_team() team4 = make_phony_team() group = Group() group.group_letter = 'A' group.save() group.teams = [team1, team2, team3, team4] fixture = Fixture() fixture.home_team = team1 fixture.away_team = team2 fixture.save() group.fixtures.add(fixture) fixture = Fixture() fixture.home_team = team3 fixture.away_team = team4 fixture.save() group.fixtures.add(fixture) fixture = Fixture() fixture.home_team = team1 fixture.away_team = team3 fixture.save() group.fixtures.add(fixture) fixture = Fixture() fixture.home_team = team2 fixture.away_team = team4 fixture.save() group.fixtures.add(fixture) fixture = Fixture() fixture.home_team = team1 fixture.away_team = team4 fixture.save() group.fixtures.add(fixture) fixture = Fixture() fixture.home_team = team2 fixture.away_team = team3 fixture.save() group.fixtures.add(fixture) group.save() return group
def group_create_personality_based(request, assignment_id): assignment = get_object_or_404(Assignment, id=assignment_id) # students = assignment.discipline.group.profiles.filter(student=True) students = [] for profile in assignment.discipline.group.profiles.all(): if profile.is_student(): students.append(profile) if request.method == 'POST': form = PersonalityBasedGroupForm(len(students), request.POST) if form.is_valid(): if form.cleaned_data['algorithm'] == '1': groups_members = bruteforce_group_formation(students, form.cleaned_data['number']) elif form.cleaned_data['algorithm'] == '2': groups_members = random_best_group_formation(students, form.cleaned_data['number']) else: groups_members = random_group_formation(students, form.cleaned_data['number']) for i in xrange(len(groups_members)): group = Group() group.name = form.cleaned_data['name'] + ' ' + str(i + 1) group.save() assignment.group.add(group) for member in groups_members[i]: group.profiles.add(member) group.profiles.add(assignment.discipline.teacher.profile) return HttpResponseRedirect(reverse("educational:assignment_detail", kwargs={'pk': assignment.pk})) else: form = PersonalityBasedGroupForm(len(students)) return render(request, 'educational/teacher/group_create_personality_based.html', {'form': form})
def test_group(self): group = Group() group.name = "Test Group" group.save() test_group = Group.objects.get(id=group.id) self.assertEquals(test_group, group) self.assertEquals(test_group.name, "Test Group") self.assertEquals(test_group.date_created, group.date_created) group.delete()
def group(request): '''Creates a view of group to add a new group reading the user posted data.''' groups = Group.objects.all() if request.method == 'POST': form = GroupForm(request.POST) if form.is_valid(): group_code = form.cleaned_data['group_code'] name = form.cleaned_data['name'] description = form.cleaned_data['description'] try: group = Group() group.group_code = group_code group.name = name group.description = description group.save() except: pass return HttpResponseRedirect(reverse('index')) else: form = GroupForm() return render(request, 'groups/group.html', {'groups' : groups, 'form' : form} )
def get(self, request): gs = Group.gets_new(limit=50) groups = MyGroupsView.parse_group_info(Group.get_more_info(gs), request.user) return render_to_response('groups/public.html', {'groups': json.dumps(groups)})
def create_test_offering(): """ main test course: interesting data for grades, marking, submission, groups """ from grades.models import Activity, LetterActivity, CalNumericActivity, CalLetterActivity from submission.models import SubmissionComponent from submission.models.code import CodeComponent from submission.models.pdf import PDFComponent from groups.models import Group, GroupMember from marking.models import ActivityComponent crs = CourseOffering.objects.get(slug=TEST_COURSE_SLUG) crs.set_labtut(True) crs.set_url("http://www.cs.sfu.ca/CC/165/common/") crs.set_taemail("*****@*****.**") crs.save() # create example activities a1 = NumericActivity.objects.get(offering=crs, slug='a1') a2 = NumericActivity(offering=crs, name="Assignment 2", short_name="A2", status="URLS", due_date=crs.semester.start + datetime.timedelta(days=70), percent=10, group=True, max_grade=20, position=2) a2.set_url("http://www.cs.sfu.ca/CC/165/common/a2") a2.save() pr = LetterActivity(offering=crs, name="Project", short_name="Proj", status="URLS", due_date=crs.semester.start + datetime.timedelta(days=80), percent=40, group=True, position=3) pr.save() re = LetterActivity(offering=crs, name="Report", short_name="Rep", status="URLS", due_date=crs.semester.start + datetime.timedelta(days=81), percent=10, group=False, position=4) re.save() ex = NumericActivity(offering=crs, name="Final Exam", short_name="Exam", status="URLS", due_date=None, percent=30, group=False, max_grade=90, position=5) ex.save() to = CalNumericActivity(offering=crs, name="Final Percent", short_name="Perc", status="INVI", due_date=None, percent=0, group=False, max_grade=100, formula="[[activitytotal]]", position=6) to.save() to = CalLetterActivity(offering=crs, name="Letter Grade", short_name="Letter", status="INVI", due_date=None, percent=0, group=False, numeric_activity=to, position=6) to.save() # make A1 submittable and markable s = CodeComponent(activity=a1, title="Code File", description="The code you're submitting.", allowed=".py,.java") s.save() s = PDFComponent(activity=a1, title="Report", description="Report on what you did.", specified_filename="report.pdf") s.save() m = ActivityComponent(numeric_activity=a1, max_mark=5, title="Part 1", description="Part 1 was done well and seems to work.", position=1) m.save() m = ActivityComponent(numeric_activity=a1, max_mark=5, title="Part 2", description="Part 2 was done well and seems to work.", position=2) m.save() # create some groups members = list(Member.objects.filter(offering=crs, role='STUD')) random.shuffle(members) m = members.pop() g = Group(name="SomeGroup", courseoffering=crs, manager=m) g.save() for m in [m, members.pop()]: gm = GroupMember(group=g, student=m, confirmed=True, activity=a2) gm.save() m = members.pop() g = Group(name="AnotherGroup", courseoffering=crs, manager=m) g.save() for m in [m, members.pop(), members.pop()]: gm = GroupMember(group=g, student=m, confirmed=True, activity=a2) gm.save() gm = GroupMember(group=g, student=m, confirmed=True, activity=pr) gm.save() return itertools.chain( Activity.objects.all(), NumericActivity.objects.all(), LetterActivity.objects.all(), CalNumericActivity.objects.all(), CalLetterActivity.objects.all(), SubmissionComponent.objects.all(), CodeComponent.objects.all(), PDFComponent.objects.all(), Group.objects.all(), GroupMember.objects.all(), ActivityComponent.objects.all(), )
def get(self, request, gid): group = Group.get(gid) has_joined = UserGroupRel.has_joined(request.user.id, gid) info = json.dumps(group.get_info(has_joined)) userinfo = json.dumps(group.get_creator_info()) return render_to_response('groups/group.html', {'group': info, 'user': userinfo, 'paid': json.dumps(has_joined)})
def get(self, request): user = request.user gs = Group.gets_joined(user.id) groups = MyGroupsView.parse_group_info([g.get_info() for g in gs], user) return render_to_response('groups/paid_group.html', {'groups': json.dumps(groups)})