def sign_up(request): if request.method == 'GET': return render(request, 'auth/sign_up.html') elif request.method == 'POST': request_body = dict(request.POST) name = request_body.get('name')[0] surname = request_body.get('surname')[0] email = request_body.get('email')[0] password = request_body.get('password')[0] retype_password = request_body.get('retype-password')[0] if name == '' or surname == '' or email == '' or password == '' or password != retype_password: return render( request, 'auth/sign_up.html', {'error': 'The form has been filled out incorrectly'}) new_auth_user = AuthUser(first_name=name, last_name=surname, username=email, email=email) new_auth_user.set_password(password) new_auth_user.save() auth_login(request, new_auth_user) new_user = User(name=name, surname=surname, email=email, auth_user=new_auth_user) new_user.save() return redirect('/')
def update_poll_participants_and_notify(self, old_participants, new_participants, poll, user, title, link): old_participants = set(old_participants) new_participants = set(new_participants) old_new = old_participants.difference(new_participants) new_old = new_participants.difference(old_participants) for par_email in old_new: try: par = User.objects.get(email=par_email) meet_par = MeetingParticipant.objects.get(participant=par, meeting=poll.meeting) meet_par.delete() except: pass for par_email in new_old: try: user = User.objects.get(email=par_email) meetingParticipant = MeetingParticipant(meeting=poll.meeting, participant=user) meetingParticipant.save() except: user = User(username=par_email, email=par_email, password='') user.save() meetingParticipant = MeetingParticipant(meeting=poll.meeting, participant=user) meetingParticipant.save() if new_old: send_email_add_participant(user, title, link, list(new_old), True) if old_new: send_email_add_participant(user, title, link, list(old_new), False) return old_participants.union(new_participants)
def create_user_account(response): if response.method == "POST": form = NewUserAccountForm(response.POST) if form.is_valid(): email = form.cleaned_data["email"] password1 = form.cleaned_data["password1"] password2 = form.cleaned_data["password2"] first_name, last_name = form.cleaned_data['first_name'], form.cleaned_data['last_name'] username = form.cleaned_data["user_name"] date_of_birth = response.POST['birth_date'] if password1 == password2: u = User(first_name=first_name, last_name=last_name, username=username, email=email, password=password1, birth_date=date_of_birth, logged_in=True) u.save() return redirect('authentication:profile') else: form = NewUserAccountForm() heading = "The passwords do not match. Try again." context_vars = {'form': form, 'heading': heading, 'val': 'CREATE ACCOUNT'} return render(response, "authenticationh/new_user_account.html", context_vars) elif response.method == "GET": email = response.session.get('email', None) form = NewUserAccountForm(initial={'email': email}) min_date = tz.localtime(tz.now()).date() min_year = min_date.year-100 context_vars = {'method': 'post', 'action': '/register/register/', 'form': form, 'heading': 'Welcome to my Chess Website! Please create your account here.', 'val': 'CREATE ACCOUNT', 'max': tz.localtime(tz.now()).date(), 'min': datetime.date(min_year, min_date.month, min_date.day), 'date_val': date(tz.localtime(tz.now()).date().year, 1, 1), 'date': True} return render(response, 'authentication/new_user_account.html', context_vars) else: return HttpResponseNotAllowed(['GET', 'POST'])
def test_assess_character_user_as_main(self): user = User(main_character_id=self.char.id) user.save() logger.debug("-----------------------------------------") logger.debug(" test_assess_character_user_as_main") logger.debug("-----------------------------------------") assess_character_owner(self.char) self.assertEqual(self.char.user, user)
def setUp(self): self.user = User( username="******", is_staff=True, is_superuser=True, ) self.user.set_password("bar") self.user.save() self.client.login(username="******", password="******")
def test_add_voters_age_fail_voting_started(self): census_before = len(Census.objects.all().values_list('voting_id', flat=True)) admin = User(email='*****@*****.**', password='******') admin.is_staff = True admin.save() user1 = User(email='*****@*****.**', password='******', city='sevilla', sex='M', birthdate=date(year=2000, month=1, day=1)) user1.save() voting_id = "40" voting = Voting.objects.get(pk=40) voting.start_date = timezone.now() voting.save() self.client.force_login(admin) response2 = self.client.get( '/census/addAllByAge/?voting_id={}&younger={}&older={}'.format( voting_id, 100, 0)) census_after = len(Census.objects.all().values_list('voting_id', flat=True)) self.assertEqual(response2.status_code, 302) self.assertTrue(census_after == census_before)
def test_add_voter_custom_fail_not_staff(self): census_before = len(Census.objects.all().values_list('voting_id', flat=True)) admin = User(email='*****@*****.**', password='******') admin.is_staff = False admin.save() user1 = User(email='*****@*****.**', password='******', city='sevilla', sex='M', birthdate=date(year=2000, month=1, day=1)) user1.save() self.client.force_login(admin) voting = Voting.objects.get(pk=40) response = self.client.post( '/census/addCustomCensus', { 'voting': voting.pk, 'city': 'sevilla', 'sex': 'M', 'age_initial_range': '22/12/1990', 'age_final_range_election': '22/12/2020' }) census_after = len(Census.objects.all().values_list('voting_id', flat=True)) self.assertEqual(response.status_code, 302) self.assertTrue(census_after == census_before)
def test_assess_character_user_with_bad_api(self): logger.debug("-----------------------------------------") logger.debug(" test_assess_character_user_with_bad_api") logger.debug("-----------------------------------------") self.api.is_valid = False user = User(main_character_id=999999) user.save() self.api.owner = user self.api.save() assess_character_owner(self.char) self.assertFalse(self.char.user)
def test_assess_character_user_with_bad_api(self): logger.debug("-----------------------------------------") logger.debug(" test_assess_character_user_with_bad_api") logger.debug("-----------------------------------------") self.api.is_valid=False user = User(main_character_id=999999) user.save() self.api.owner = user self.api.save() assess_character_owner(self.char) self.assertFalse(self.char.user)
def test_assess_character_user_with_good_api(self): logger.debug("-----------------------------------------") logger.debug(" test_assess_character_user_with_good_api") logger.debug("-----------------------------------------") self.api.is_valid = True user = User(main_character_id=999999) user.save() self.api.owner = user self.api.save() self.api.characters.add(self.char) assess_character_owner(self.char) self.assertEqual(self.char.user, user)
def test_str(self): """ Test str representation of User """ user = User( title='Dr', first_name='Chris', last_name='Bartlett', email='*****@*****.**', ) self.assertEqual( user.__str__(), 'Dr Chris Bartlett ([email protected])' )
def create(self, validated_data): """ Create and return user instance, given validate data """ user = User() user.email = validated_data.get('email') user.set_password(validated_data.get('password')) user.phone_number = validated_data.get('phone_number') user.username = validated_data.get('username') user.is_active = False user.save() return user
def test_assess_character_user_with_good_api(self): logger.debug("-----------------------------------------") logger.debug(" test_assess_character_user_with_good_api") logger.debug("-----------------------------------------") self.api.is_valid=True user = User(main_character_id=999999) user.save() self.api.owner = user self.api.save() self.api.characters.add(self.char) assess_character_owner(self.char) self.assertEqual(self.char.user, user)
class Login(BaseView, PhoneMixin): def get_sms_code(self, request): sms_code = request.POST.get('key') user_sms_code = redis.get('nedviga_user_sms_{}'.format(self.phone)) if user_sms_code: if int(user_sms_code) == int(sms_code): if not User.objects.filter(phone=self.phone): self.user = User() self.user.phone = self.phone self.user.set_password(DEFAULT_PASSWORD) self.user.save() else: return self.render_internal_error('Invalid sms-code') else: return self.render_internal_error('Sms-code expired') def post(self, request): """ :param request: :param phone: номер телефона :param sms_code: sms код проверки :return: Авторизует пользователя по номеру телефона и sms-коду Варианты ошибок: 'User not registered' - пользователь с таким телефоном не зарегистрирован 'User is blocked' - пользователь заблокирован 'Invalid sms-code' - неверный sms-код авторизации """ result = self.get_phone(request) if result: return result result = self.get_user(self.phone, False) if result: return result result = self.get_sms_code(request) if result: return result # еще раз вытаскиваем юзера, чтобы django его авторизировала, просто User передать нельзя self.user = authenticate(phone=self.phone, password=DEFAULT_PASSWORD) # удаляем все другие сессии этого пользователя, чтобы был залогинен всегда с одного устройства my_old_sessions = Session.objects.all() for row in my_old_sessions: if row.get_decoded().get("_auth_user_id") == self.user.id: row.delete() # теперь спокойно логиним login(request, self.user) return self.render_json_response(data={'sessionid': request.session.session_key})
def generate_batch_wishes(self, n_propositions=10, n_students=168): """ Creates a campaign with propositions, users, and 4 categories in which the students are distributed with the probabilities 0.8, 0.1, 0.06, 0.04 """ np.random.seed(0) campaign = Campaign(name="Batch campaign", manager_id="17bocquet") campaign.save() propositions = [] for i in range(n_propositions): proposition = Proposition( campaign_id=campaign.id, name="proposition_{}".format(i), # number_of_places=int(ceil(n_students / n_propositions)), TODO: remove this or restore it in the model. ) proposition.save() propositions.append(proposition) categories = [] for name in ["category_{}".format(i) for i in range(4)]: category = Category(name=name, campaign=campaign) category.save() categories.append(category) user_campaigns = [] for i in range(n_students): user = User( id="19user{}".format(i), first_name="firstname {}".format(i), last_name="lastname {}".format(i), year_of_entry=2019, email="email{}@mpt.fr".format(i), ) user.save() category = np.random.choice(categories, 1, p=[0.8, 0.1, 0.06, 0.04])[0] uc = UserCampaign(user=user, campaign=campaign, category=category) uc.save() user_campaigns.append(uc) if i < 157: # simulate that a few users didn't answer the form for (rank, proposition) in enumerate( np.random.permutation(propositions)): wish = Wish(user_campaign=uc, proposition=proposition, rank=rank) wish.save() return campaign, propositions, categories, user_campaigns
def _get_client_with_user(self, username, with_token=False): user = User(**{"username": username, "phone_number": "+77772537792", "password": "******"}) user.save() client = APIClient() if with_token: token = Token.objects.create(user=user) client.credentials(HTTP_AUTHORIZATION="Token " + token.key) client.user = user return client
def test_assess_character_user_on_last_api_invalid(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_on_last_api_invalid") logger.debug("-----------------------------------------") self.api.is_valid=False self.api.characters.add(self.char) user = User(main_character_id=99999999) user.save() self.api.owner = user self.char.user = user self.api.save() self.char.save() assess_character_owner(self.char) self.assertFalse(self.char.user)
def test_assess_character_user_on_api_invalid_as_main(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_on_api_invalid_as_main") logger.debug("-----------------------------------------") self.api.is_valid = False self.api.characters.add(self.char) user = User(main_character_id=self.char.id) user.save() self.api.owner = user self.char.user = user self.api.save() self.char.save() assess_character_owner(self.char) self.assertEqual(self.char.user, user)
def test_add_voters_registered_fail_not_staff(self): census_before = len(Census.objects.all().values_list('voting_id', flat=True)) user1 = User(email='*****@*****.**', password='******', city='sevilla', sex='M') user1.save() admin = User(email='*****@*****.**', password='******', is_staff=False) admin.save() self.client.force_login(admin) voting_id = "90" response2 = self.client.get( '/census/addAllRegistered/?voting_id={}'.format(voting_id)) census_after = len(Census.objects.all().values_list('voting_id', flat=True)) self.assertEqual(response2.status_code, 302) self.assertTrue(census_before == census_after)
def test_assess_character_user_on_last_api_invalid(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_on_last_api_invalid") logger.debug("-----------------------------------------") self.api.is_valid = False self.api.characters.add(self.char) user = User(main_character_id=99999999) user.save() self.api.owner = user self.char.user = user self.api.save() self.char.save() assess_character_owner(self.char) self.assertFalse(self.char.user)
def test_assess_character_user_on_api_invalid_as_main(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_on_api_invalid_as_main") logger.debug("-----------------------------------------") self.api.is_valid=False self.api.characters.add(self.char) user = User(main_character_id=self.char.id) user.save() self.api.owner = user self.char.user = user self.api.save() self.char.save() assess_character_owner(self.char) self.assertEqual(self.char.user, user)
def create_participants(self, meeting, participants, user): for participant in participants: try: user = User.objects.get(email=participant) meetingParticipant = MeetingParticipant(meeting=meeting, participant=user) meetingParticipant.save() except: user = User(username=participant, email=participant, password='') user.save() meetingParticipant = MeetingParticipant(meeting=meeting, participant=user) meetingParticipant.save()
def setUpClassData(cls): cls.user = User(email=mock_user1["email"], username=mock_user1["username"]) cls.user.set_password(mock_user1["password"]) cls.user.save() cls.post = Post(content="post1", author=cls.user.pk) cls.post.save()
def register(request): username = request.data.get('username') password = request.data.get('password') try: User.objects.create_user(username, password) except IntegrityError: return Response( { 'status': 'Bad Request', 'message': 'Email is already taken', }, status=status.HTTP_400_BAD_REQUEST) ok, data = User.login(request, username, password) if ok: serialized = UserSerializer(data) token = Token.objects.get_or_create(user=data)[0].key return Response({'user': serialized.data, 'token': token}) else: return Response({ 'status': 'Bad Request', 'message': data, }, status=status.HTTP_400_BAD_REQUEST)
def validate(self, data): log_data = data.copy() log_data.pop('password', None) utils.start_method_log('UserSerializer: validate', **log_data) # here data has all the fields which have validated values # so we can create a User instance out of it user = User(**data) # get the password from the data password = data.get('password') username = data.get("username") errors = {} try: # validate the password and catch the exception validate_password(password=password, user=user) # the exception raised here is different than serializers.ValidationError except ValidationError as e: logger.info('UserSerializer: validate (username: {}: password not validated!)'.format(username)) errors['password'] = list(e.messages) try: User.objects.check_username(username=username) except ValidationError as e: logger.info('UserSerializer: validate (username {} not validated!)'.format(username)) errors['username'] = e.message if errors: raise serializers.ValidationError(errors) return super(UserSerializer, self).validate(data)
def get_object(self): try: user = User.objects(id=self.kwargs['id'])[0] except IndexError: raise Http404 self.check_object_permissions(self.request, user) return user
def create(name, email, password, firm): hashed_pw = bcrypt.generate_password_hash(password).decode("utf-8") user = User(username=name, email=email, password=hashed_pw, firm=firm) db.session.add(user) db.session.commit() print("Create user: {}, {}".format(name, email))
def profile_settings(request): try: user = User.active_users('get', username=request.user.username) except User.DoesNotExist: raise Http404( 'Такого аккаунта не существует. Возможно он был заблокирован или удален' ) return render(request, 'profiles/profile_detail.html', {'user': user})
def setUp(self): self.user = User( username = "******", is_staff = True, is_superuser = True, ) self.user.set_password("bar") self.user.save() self.client.login(username="******", password="******")
def test_add_voters_registered(self): census_before = len(Census.objects.all().values_list('voting_id', flat=True)) admin = User(email='*****@*****.**', password='******') admin.is_staff = True admin.save() voting_id = "40" self.client.force_login(admin) response2 = self.client.get( '/census/addAllRegistered/?voting_id={}'.format(voting_id)) census_after = len(Census.objects.all().values_list('voting_id', flat=True)) self.assertEqual(response2.status_code, 302) self.assertTrue(census_before < census_after)
def create(self, validated_data): user = User(email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name']) user.set_password(validated_data['password']) user.is_active = True user.save() return user
def signup(request): response_dict = json.loads(request.body) email = response_dict['email'] password = response_dict['password'] hashed_password = make_password(password) if is_email_not_valid(email) or is_password_not_valid(password): message = 'Either email or password are incorrect.' response = JsonResponse({'status': False, 'message': message}) response.status_code = 400 return response u = User(email=email, password=hashed_password) u.save() token = jwt.encode({'user_id': u.id}, 'secret', algorithm='HS256') data = {'token': token.decode('utf-8'), 'user_id': u.id} return JsonResponse(data)
def test_assess_character_user_change_as_main(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_change_as_main") logger.debug("-----------------------------------------") main_user = User(main_character_id=self.char.id) main_user.save() other_user = User(main_character_id=9999999) other_user.save() self.char.user = other_user self.char.save() assess_character_owner(self.char) self.assertEqual(self.char.user, main_user)
def post(self, request): form = RegisterForm(request.POST) # check whether it's valid: if form.is_valid(): data = form.cleaned_data user = User() user.email = data['email'] user.set_password(data['password1']) user.first_name = data['first_name'] user.last_name = data['last_name'] user.save() group = Group.objects.get(name='Users') user.groups.add(group) user.save() return redirect("index") return render_to_response(self.template_name, {'form': form}, context_instance=RequestContext(request))
def handle(self, *args, **options): user_cnt = 50000 for i in range(0, user_cnt, 100): User.objects.bulk_create([ User(email=email_random_generator(), username=username_random_generator(), is_active=random.choice([True, False]), is_verified=random.choice([True, False])) for j in range(1, 101) ])
def profile_detail(request, username): try: user = User.active_users('get', username=username) if user != request.user: return HttpResponseForbidden( 'Вы не можете редактировать профиль другого пользователя') except User.DoesNotExist: raise Http404( 'Такого аккаунта не существует. Возможно он был заблокирован или удален' ) return render(request, 'profiles/profile_common.html', {'user': user})
def get(self, request, pk=None, *args, **kwargs): if not pk: users = User.objects() serializer = UserSerializer(users, many=True) return Response(serializer.data) try: user = User.objects.get(pk=pk) except: return Response({}, status=status.HTTP_204_NO_CONTENT) else: serializer = UserSerializer(user) return Response(serializer.data)
def add_to_collection(self, user, rel_path): """Adds the given user directory to collection repository with all subdirectories and files. Also sets the user permission and subscription.""" # read description file desc_parser = info.parse_description(user, rel_path) # Create root directory and save it with all subdirectories and files item = os.path.basename(rel_path) root_dir = Directory(revision=1, name=item, user_modified=user, size=WebFolder.get_dir_size(user, rel_path)) root_dir.save() info.create_traits(user, rel_path, root_dir.identifier, 1) root_dir.save_recursive(user, rel_path) root_dir.save() # Set collection attributes self.directory = root_dir self.revision = 1 self.save() self.abstract = desc_parser.get_abstract() self.details = desc_parser.get_details() self.comment = "Add the collection to the repository." self.save() for (key,value) in desc_parser.get_tags(): try: tag = Tag.objects.get(key=key, value=value) except ObjectDoesNotExist: tag = Tag(key=key, value=value) tag.save() self.tags.add(tag) # Set user access permission = UserPermission(collection=self, user=user, permission=enum.Permission.WRITE) permission.save() # Set user subscription subscription = Subscription(collection=self, user=user) subscription.save() # Update news log content = "A new collection <b>" + self.name + "</b> was added to the repository.\n" + \ "<i><b>Abstract:</b>\n" + self.abstract + "</i>" news = News(user=User.get_current_user(), content=content, collection=self) news.save()
def get_sms_code(self, request): sms_code = request.POST.get('key') user_sms_code = redis.get('nedviga_user_sms_{}'.format(self.phone)) if user_sms_code: if int(user_sms_code) == int(sms_code): if not User.objects.filter(phone=self.phone): self.user = User() self.user.phone = self.phone self.user.set_password(DEFAULT_PASSWORD) self.user.save() else: return self.render_internal_error('Invalid sms-code') else: return self.render_internal_error('Sms-code expired')
def login(request): username = request.data.get('username') password = request.data.get('password') ok, data = User.login(request, username, password) if ok: serialized = UserSerializer(data) token = Token.objects.get_or_create(user=data)[0].key return Response({'user': serialized.data, 'token': token}) else: return Response({ 'status': 'Unauthorized', 'message': data, }, status=status.HTTP_401_UNAUTHORIZED)
def update_user_permission(self, user, permission): """Grant the given user the given permission of this collection.""" if permission: if UserPermission.objects.filter(user=user, collection=self): p = UserPermission.objects.get(user=user, collection=self) p.permission = permission else: p = UserPermission(user=user, collection=self, permission=permission) p.save_all_revisions() else: p = UserPermission.objects.get(user=user, collection=self) p.delete_all_revisions() # Update news log content = "The user permissions of collection <b>" + self.name + "</b> were changed.\n" + \ "The user <b>" + user.user_name + "</b> has " + utils.enum.Permission.get_readable_permission(permission) + " access." news = News(user=User.get_current_user(), content=content, collection=self) news.save()
def update_group_permission(self, group, permission): """Grant the given group the given permission of this collection.""" if permission: if GroupPermission.objects.filter(group=group, collection=self): p = GroupPermission.objects.get(group=group, collection=self) p.permission = permission else: p = GroupPermission(group=group, collection=self, permission=permission) p.save_all_revisions() else: permission = GroupPermission.objects.get(group=group, collection=self) permission.delete_all_revisions() # Update news log content = "The group permissions of collection <b>" + self.name + "</b> were changed.\n" + \ "The group <b>" + group.group_name + "</b> has " + utils.enum.Permission.get_readable_permission(permission) + " access." news = News(user=User.get_current_user(), content=content, collection=self) news.save()
def update_public_access(self, access): """Set public access to all revisions of the collection. Parameter access is a boolean value.""" if(self.public_access!=access): self.public_access = access self.save() for c in self.get_all_revisions(): c.public_access = access c.save() # Update news log if access: readable_access="public" else: readable_access="not public" content = "The permissions of collection <b>" + self.name + "</b> were changed.\n" + \ "The collection is " + readable_access + "." news = News(user=User.get_current_user(), content=content, collection=self) news.save()
def register(request): username = request.data.get('username') password = request.data.get('password') try: User.objects.create_user(username, password) except IntegrityError: return Response({ 'status': 'Bad Request', 'message': 'Email is already taken', }, status=status.HTTP_400_BAD_REQUEST) ok, data = User.login(request, username, password) if ok: serialized = UserSerializer(data) token = Token.objects.get_or_create(user=data)[0].key return Response({'user': serialized.data, 'token': token}) else: return Response({ 'status': 'Bad Request', 'message': data, }, status=status.HTTP_400_BAD_REQUEST)
def test_assess_character_user_change_on_bad_api(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_change_on_bad_api") logger.debug("-----------------------------------------") good_user = User(main_character_id=8888888) good_user.save() bad_user = User(main_character_id=9999999) bad_user.save() self.api.characters.add(self.char) self.api.owner = good_user self.api.is_valid=True bad_api = EVEApiKeyPair(id=99999999, vcode="test api please ignore", owner=bad_user) bad_api.is_valid=False self.char.user = bad_user self.api.save() bad_api.save() bad_api.characters.add(self.char) self.char.save() assess_character_owner(self.char) self.assertEqual(self.char.user, good_user)
def test_assess_character_user_change_on_new_api(self): logger.debug("-----------------------------------------") logger.debug("test_assess_character_user_change_on_new_api") logger.debug("-----------------------------------------") first_user = User(main_character_id=8888888) first_user.save() new_user = User(main_character_id=9999999) new_user.save() self.api.characters.add(self.char) self.api.owner = first_user self.api.is_valid=True self.api.save() other_api = EVEApiKeyPair(id=9999999, vcode="test api please ignore", owner=new_user) other_api.is_valid=True other_api.save() other_api.characters.add(self.char) self.char.user = first_user self.char.save() assess_character_owner(self.char) self.assertFalse(self.char.user)
def push_local_revision(self, user, rel_path, prev_col, comment): """Push the local revision to the repository.""" prev_max_revision = Collection.objects.filter(identifier=prev_col.identifier).aggregate(Max('revision'))['revision__max'] # collection is at newest revision if prev_col.revision == prev_max_revision: # read description file desc_parser = info.parse_description(user, rel_path) # Create root directory and update it with the local revision item = os.path.basename(rel_path) root_dir = Directory(identifier=prev_col.directory.identifier, revision=prev_col.revision+1, name=item, user_modified=user, size=WebFolder.get_dir_size(user, rel_path)) root_dir.save() info.create_traits(user, rel_path, root_dir.identifier, root_dir.revision) root_dir.push_recursive(user, rel_path, prev_col.directory) if root_dir.hash == prev_col.directory.hash: root_dir.delete() raise NoLocalChangesException() else: # Set collection attributes self.identifier = prev_col.identifier self.directory = root_dir self.revision = prev_col.revision+1 self.save() self.abstract = desc_parser.get_abstract() self.details = desc_parser.get_details() self.comment = comment self.save() for (key,value) in desc_parser.get_tags(): try: tag = Tag.objects.get(key=key, value=value) except ObjectDoesNotExist: tag = Tag(key=key, value=value) tag.save() self.tags.add(tag) # Set user access UserPermission.update(self) GroupPermission.update(self) # Set user subscription subscription = Subscription(collection=self, user=user) subscription.save() # Update news log content = "The collection <b>" + self.name + "</b> was updated to revision " + \ str(self.revision) + ".\n" + "<i><b>Comment:</b>\n" + self.comment + "</i>" news = News(user=User.get_current_user(), content=content, collection=self) news.save() # collection is not at newest revision else: raise NotNewestRevisionException()
def save_user(email, name_surname, password): user = User(email=email, name_surname= name_surname, password=password) user.save() return user
def test_str_method(self): user = User(email='*****@*****.**') self.assertEqual(user.__str__(), '*****@*****.**')
def test_get_short_name(self): user = User(first_name='Admin', last_name='User') self.assertEqual(user.get_short_name(), 'Admin')
class VersionAdminTest(TestCase): urls = "reversion.tests" def setUp(self): self.user = User( username = "******", is_staff = True, is_superuser = True, ) self.user.set_password("bar") self.user.save() self.client.login(username="******", password="******") def testAutoRegisterWorks(self): self.assertTrue(reversion.is_registered(ChildTestAdminModel)) self.assertTrue(reversion.is_registered(ParentTestAdminModel)) def testRevisionSavedOnPost(self): self.assertEqual(ChildTestAdminModel.objects.count(), 0) # Create an instance via the admin. response = self.client.post("/admin/auth/childtestadminmodel/add/", { "parent_name": "parent instance1 version1", "child_name": "child instance1 version1", "_continue": 1, }) self.assertEqual(response.status_code, 302) obj_pk = response["Location"].split("/")[-2] obj = ChildTestAdminModel.objects.get(id=obj_pk) # Check that a version is created. versions = reversion.get_for_object(obj) self.assertEqual(versions.count(), 1) self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version1") self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version1") # Save a new version. response = self.client.post("/admin/auth/childtestadminmodel/%s/" % obj_pk, { "parent_name": "parent instance1 version2", "child_name": "child instance1 version2", "_continue": 1, }) self.assertEqual(response.status_code, 302) # Check that a version is created. versions = reversion.get_for_object(obj) self.assertEqual(versions.count(), 2) self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version2") self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version2") # Check that the versions can be listed. response = self.client.get("/admin/auth/childtestadminmodel/%s/history/" % obj_pk) self.assertContains(response, "child instance1 version2") self.assertContains(response, "child instance1 version1") # Check that a version can be rolled back. response = self.client.post("/admin/auth/childtestadminmodel/%s/history/%s/" % (obj_pk, versions[1].pk), { "parent_name": "parent instance1 version3", "child_name": "child instance1 version3", }) self.assertEqual(response.status_code, 302) # Check that a version is created. versions = reversion.get_for_object(obj) self.assertEqual(versions.count(), 3) self.assertEqual(versions[0].field_dict["parent_name"], "parent instance1 version3") self.assertEqual(versions[0].field_dict["child_name"], "child instance1 version3") # Check that a deleted version can be viewed. obj.delete() response = self.client.get("/admin/auth/childtestadminmodel/recover/") self.assertContains(response, "child instance1 version3") # Check that a deleted version can be recovered. response = self.client.post("/admin/auth/childtestadminmodel/recover/%s/" % versions[0].pk, { "parent_name": "parent instance1 version4", "child_name": "child instance1 version4", }) obj = ChildTestAdminModel.objects.get(id=obj_pk) def tearDown(self): self.client.logout() self.user.delete() del self.user ChildTestAdminModel.objects.all().delete()