Exemplo n.º 1
0
    def create(self, request, *args, **kwargs) -> Response:
        eat_habits_formatted = create_missing_eat_habits(request)

        if eat_habits_formatted and len(eat_habits_formatted) > 0:
            request.data['eat_habit'] = eat_habits_formatted

        registration: event_models.Registration = self.participant_initialization(
            request)

        if request.data.get('age'):
            request.data['birthday'] = timezone.now() - relativedelta(
                years=int(request.data.get('age')))

        request.data['registration'] = registration.id
        if request.data.get('first_name') is None and request.data.get(
                'last_name') is None:
            max_num = self.get_queryset().count()
            request.data['first_name'] = 'Teilnehmer'
            request.data['last_name'] = max_num + 1
        if request.data.get('booking_option') is None:
            request.data[
                'booking_option'] = registration.event.bookingoption_set.first(
                ).id
        if registration.event.registration_deadline < timezone.now():
            request.data[
                'needs_confirmation'] = event_choices.ParticipantActionConfirmation.AddCompletyNew

        return super().create(request, *args, **kwargs)
Exemplo n.º 2
0
    def by_days_range(self, days_ago=12, number_of_days=3):
        if number_of_days > days_ago:
            number_of_days = days_ago
        start_date = timezone.now() - timedelta(days=days_ago)
        end_date = timezone.now() - timedelta(days=days_ago - number_of_days)

        return self.by_range(start_date, end_date=end_date)
Exemplo n.º 3
0
    def update(self, request, *args, **kwargs) -> Response:
        print(request.data)
        eat_habits_formatted = create_missing_eat_habits(request)

        if eat_habits_formatted and len(eat_habits_formatted) > 0:
            request.data['eat_habit'] = eat_habits_formatted

        registration: event_models.Registration = self.participant_initialization(
            request)
        participant: event_models.RegistrationParticipant = self.get_object()

        if participant.deactivated:
            if request.data.get(
                    'activate'
            ) and registration.event.registration_deadline >= timezone.now():
                request.data['deactivated'] = False
                request.data[
                    'needs_confirmation'] = event_choices.ParticipantActionConfirmation.Nothing
            elif registration.event.last_possible_update >= timezone.now():
                request.data['deactivated'] = False
                request.data[
                    'needs_confirmation'] = event_choices.ParticipantActionConfirmation.AddFromExisting

        request.data['generated'] = False
        return super().update(request, *args, **kwargs)
Exemplo n.º 4
0
 def estado(self):
     if self.revocada:
         return "Revocada"
     elif self.fecha_inicio and self.fecha_inicio > timezone.now():
         return "No activa"
     elif self.fecha_expiracion and self.fecha_expiracion < timezone.now():
         return "Expirada"
     return "Activa"
Exemplo n.º 5
0
    def by_weeks_range(self, weeks_ago=3, number_of_weeks=2):
        if number_of_weeks > weeks_ago:
            number_of_weeks = weeks_ago
        day_ago_start = weeks_ago * 7
        day_ago_end = day_ago_start - (number_of_weeks * 7)
        start_date = timezone.now() - timedelta(days=day_ago_start)
        end_date = timezone.now() - timedelta(days=day_ago_end)

        return self.by_range(start_date, end_date=end_date)
Exemplo n.º 6
0
 def test_remaining_job_queue(self):
     s = RemainingJobs.objects.create(lower_date_bound=timezone.now() -
                                      timedelta(hours=2),
                                      upper_date_bound=timezone.now(),
                                      reason_for_failure="nope")
     x = RemainingJobs.objects.create(lower_date_bound=timezone.now() -
                                      timedelta(hours=1),
                                      upper_date_bound=timezone.now(),
                                      reason_for_failure="nope")
     assert RemainingJobs.get_oldest_job(
     ) == s, "should be oldest job in the queue"
Exemplo n.º 7
0
    def destroy(self, request, *args, **kwargs) -> Response:
        registration: event_models.Registration = self.get_object()
        participants_count = event_models.RegistrationParticipant.objects.filter(
            registration=registration.id).count()
        if participants_count == 0:
            return super().destroy(request, *args, **kwargs)

        if registration.event.last_possible_update < timezone.now():
            raise event_api_exceptions.TooLate
        elif registration.event.registration_deadline < timezone.now():
            raise event_api_exceptions.TooManyParticipants

        return super().destroy(request, *args, **kwargs)
Exemplo n.º 8
0
def create_post(N):
    fake = Faker()
    for _ in range(N):
        id = random.randint(1, 4)
        title = fake.name()
        status = random.choice(['published', 'draft'])
        Post.objects.create(
            title=title + " Post!!!",
            author=User.objects.get(id=id),
            slug="-".join(title.lower().split()),
            body=fake.text(),
            created=timezone.now(),
            updated=timezone.now(),
        )
Exemplo n.º 9
0
    def test_section_user_does_not_own_section(self):
        """
        Test when a user attempts to access a section that they don't own.
        """
        # create sample report with user 2
        report = Report.objects.create(user_id=self.test_user_2,
                                       title="Report Title",
                                       date_created=timezone.now(),
                                       reference_number="1234")
        report.save()

        # create sample section
        section_0 = Section.objects.create(
            report_id=report,
            auto_submit=False,
            required=False,
            completed=False,
            title='Section Zero',
            html_description='<p>Description zero</p>',
            number=0)
        section_0.save()

        # try to put with user 1
        factory = APIRequestFactory()
        put_section_request = factory.put('/api/v1/section/1',
                                          {'key': 'value'})
        force_authenticate(put_section_request, user=self.test_user_1)
        result = section(put_section_request, 1)
        self.assertEqual(result.status_code, 401)
Exemplo n.º 10
0
Arquivo: views.py Projeto: alyuv/uamc
    def get_queryset(self):
        geoJsonWareps = dict()
        geoJsonStormWareps = {
            "type": "FeatureCollection",
            "metadata": {
                "generated": "",
                "url": "namc.com.ua",
                "title": "Ukraine Actuals Storm Wareps",
            },
            "features": []
        }
        geoJsonAviaWareps = {
            "type": "FeatureCollection",
            "metadata": {
                "generated": "",
                "url": "namc.com.ua",
                "title": "Ukraine Actuals Avia Wareps",
            },
            "features": []
        }
        queryset = WAREP.objects.select_related('station').filter(valid_end__gte=timezone.now()).order_by('-valid_end')

        for warep in queryset:
            jsonWarep = self.generateGeoJson(warep)
            if warep.message.find('STORM') > -1:
                geoJsonStormWareps['features'].append(jsonWarep)
            elif warep.message.find('AVIA') > -1:
                geoJsonAviaWareps['features'].append(jsonWarep)
            geoJsonWareps = {'storm': json.dumps(geoJsonStormWareps), 'avia': json.dumps(geoJsonAviaWareps)}
        return geoJsonWareps
Exemplo n.º 11
0
def checkin(request):
    assert isinstance(request, HttpRequest)
    entryList=Entry.objects.all().filter(timeout=None)
    count=entryList.count()
    #utc_dt = datetime.now(timezone.utc)
    #date = utc_dt.astimezone()
    date=timezone.now()
    daydate=d.today()
    if request.method=="POST":
        form=NameForm(request.POST)        
        if form.is_valid():
            name,sk=form.cleaned_data['your_name'],form.cleaned_data['secret_key']
            exist=Entry.objects.filter(name=name,secretkey=sk)
            if exist.count()>0:
                return render(request,"checkin.html",
            {'entryList':entryList if count>0 else None,
            'form':NameForm(),'date':daydate,
            'status':'Already exist' })    

            entry=Entry(name=form.cleaned_data['your_name'] ,secretkey=form.cleaned_data['secret_key'],date=date,timein=date)
            entry.save()
            return HttpResponseRedirect(reverse('checkin'))
    else:
        form=NameForm()
    return render(request,"checkin.html",{'entryList':entryList if count>0 else None,'form':form,'date':daydate,'status':"" })
Exemplo n.º 12
0
 def get_queryset(self):
     return [
         f.from_user
         for f in Friend.objects.select_related("from_user").filter(
             to_user=self.request.user,
             from_user__lobby_expiration__gt=timezone.now()).all()
     ]
Exemplo n.º 13
0
def getDoctor_PatientEstimatedTime(patient, doctor):
    timepp = doctor.timepp

    timefpp = doctor.timefpp
    q_details = registration_models.appointmentQueue.objects.filter(
        doctor_required=doctor, actual_time=None)
    patientAhead = 0
    followUpPatientAhead = 0
    currentPatientInTime = None
    for pats in q_details:
        if (pats.patient == patient):
            currentPatientInTime = pats.time_in
            break
    time_now = timezone.now()
    for pats in q_details:
        if (currentPatientInTime > pats.time_in and pats.patient != patient):
            if (pats.is_follow_up == True):
                followUpPatientAhead = followUpPatientAhead + 1
            else:
                patientAhead = patientAhead + 1

    estimatedTime = timepp * (patientAhead) + timefpp * (followUpPatientAhead)
    return {
        "patientAhead": (patientAhead + followUpPatientAhead),
        "estimatedTime": estimatedTime
    }
Exemplo n.º 14
0
    def post(self, request):
        serializer = LobbyExpirationSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors,
                            status=rest_framework.status.HTTP_400_BAD_REQUEST)

        new_lobby_expiration = serializer.validated_data["lobby_expiration"]

        with transaction.atomic():
            # lazy ff request expiration
            if min(request.user.lobby_expiration,
                   new_lobby_expiration) < timezone.now():
                print(
                    f"Deleting expired requests to and from {request.user}..."
                )  # TODO: Replace with better logging.
                FFRequest.objects.filter(
                    status=FFRequestStatusEnum.PENDING.value,
                    sender=request.user).update(
                        status=FFRequestStatusEnum.EXPIRED.value)
                FFRequest.objects.filter(
                    status=FFRequestStatusEnum.PENDING.value,
                    receiver=request.user).update(
                        status=FFRequestStatusEnum.EXPIRED.value)

            # print("Updating lobby expiration for a user from", repr(
            #     request.user.lobby_expiration), "to", repr(new_lobby_expiration))
            request.user.lobby_expiration = new_lobby_expiration
            request.user.save()

        return HttpResponse(status=200)
Exemplo n.º 15
0
def get_time_difference(value):
    value = value.astimezone(get_localzone())
    now = timezone.now().astimezone(get_localzone())
    try:
        return now - value
    except:
        return value
Exemplo n.º 16
0
    def clean(self):
        cleaned_data = super(EventForm, self).clean()
        title = cleaned_data.get('title')
        description = cleaned_data.get('description')
        location = cleaned_data.get('location')
        start_time = cleaned_data.get('start_time')
        end_time = cleaned_data.get('end_time')

        # DateTime Sorting Validation
        current_date_time = timezone.localtime(
            timezone.now()).replace(microsecond=0)
        time_diff = start_time - current_date_time

        if time_diff.total_seconds() < 7200:
            raise forms.ValidationError(
                'The minimum event time is 2 hours after system time')

        elif start_time > end_time:
            raise forms.ValidationError(
                'Start time cannot be greater than End Time')

        elif start_time == end_time:
            raise forms.ValidationError(
                'Start time cannot be equal to End Time')
        elif title == "a":
            raise forms.ValidationError('Title error')
Exemplo n.º 17
0
 def get_queryset(self):
     queryset = super().get_queryset()
     days_count = self.request.query_params.get('day', 0)
     if days_count > 0:
         start_date = timezone.now() - timedelta(days=days_count)
         queryset = queryset.filter(created_at__gte=start_date)
     return queryset
Exemplo n.º 18
0
    def participant_initialization(self, request) -> event_models.Registration:
        input_serializer = registration_serializers.RegistrationParticipantPutSerializer(
            data=request.data)
        input_serializer.is_valid(raise_exception=True)

        registration_id = self.kwargs.get("registration_pk", None)
        registration: event_models.Registration = get_object_or_404(
            event_models.Registration, id=registration_id)

        if registration.event.registration_start > timezone.now():
            raise event_api_exceptions.TooEarly
        elif self.action != 'destroy' and registration.event.last_possible_update < timezone.now(
        ):
            raise event_api_exceptions.TooLate

        return registration
Exemplo n.º 19
0
def _get_oauth2_session(social_account):
    refresh_token_url = FirefoxAccountsOAuth2Adapter.access_token_url
    social_token = social_account.socialtoken_set.first()

    def _token_updater(new_token):
        social_token.token = new_token['access_token']
        social_token.token_secret = new_token['refresh_token']
        social_token.expires_at = (
            timezone.now() + timedelta(seconds=int(new_token['expires_in'])))
        social_token.save()

    client_id = social_token.app.client_id
    client_secret = social_token.app.secret

    extra = {
        'client_id': client_id,
        'client_secret': client_secret,
    }

    expires_in = (social_token.expires_at - timezone.now()).total_seconds()
    token = {
        'access_token': social_token.token,
        'refresh_token': social_token.token_secret,
        'token_type': 'Bearer',
        'expires_in': expires_in
    }

    client = OAuth2Session(client_id,
                           token=token,
                           auto_refresh_url=refresh_token_url,
                           auto_refresh_kwargs=extra,
                           token_updater=_token_updater)
    return client
Exemplo n.º 20
0
    def get_context_data(self, **kwargs):
        context = super(ServiceDetailView, self).get_context_data(**kwargs)

        date = self.request.GET.get('date')
        if date:
            try:
                date = datetime.strptime(date, '%Y-%m-%d').date()
            except ValueError:
                date = None
        if not date:
            date = timezone.now().date()
        context['timetables'] = timetable_from_service(self.object, date)

        if context.get('timetables'):
            for table in context['timetables']:
                table.groupings = [grouping for grouping in table.groupings if grouping.rows and grouping.rows[0].times]
                for grouping in table.groupings:
                    grouping.rows = [row for row in grouping.rows if any(row.times)]
                    stops_id = []
                    for row in grouping.rows:
                        stops_id.append(row.part.stop.atco_code)
                    stops_dict = {stop.pk: stop for stop in Stop.objects.filter(atco_code__in=stops_id)}
                    for row in grouping.rows:
                        row.part.stop.stop = stops_dict.get(row.part.stop.atco_code)

        return context
Exemplo n.º 21
0
 def date_diff2(self):
     hoje = timezone.now()
     tempocorrido = (hoje - self.datainicio).days
     tempocorrido = tempocorrido / 7
     if tempocorrido < 1:
         tempocorrido = 1
     return round(tempocorrido)
Exemplo n.º 22
0
    def test_section_report_already_submitted(self):
        """
        Test what happens when a report has already been submitted(finalized).
        """
        # create sample report already submitted
        report = Report.objects.create(user_id=self.test_user_1,
                                       title="Report Title",
                                       date_created=timezone.now(),
                                       reference_number="1234",
                                       submitted=True)
        report.save()

        # create sample section
        section_0 = Section.objects.create(
            report_id=report,
            auto_submit=False,
            required=False,
            completed=False,
            title='Section Zero',
            html_description='<p>Description zero</p>',
            number=0)
        section_0.save()

        # try to put
        factory = APIRequestFactory()
        put_section_request = factory.put('/api/v1/section/1',
                                          {'key': 'value'})
        force_authenticate(put_section_request, user=self.test_user_1)
        result = section(put_section_request, 1)
        self.assertEqual(result.status_code, 409)
Exemplo n.º 23
0
def menu_list(request):
    # displays the listing of all Menus that havent reach their expiration date
    all_menus = Menu.objects.all().prefetch_related('items')
    query = Q(expiration_date__gte=timezone.now()) | Q(
        expiration_date__isnull=True)
    menus = all_menus.filter(query).order_by('-expiration_date')
    return render(request, 'menu/list_all_current_menus.html',
                  {'menus': menus})
Exemplo n.º 24
0
def filter_suspension(request):
    user_profile = UserProfile.objects.all()
    # suspend_user = []  # list of suspended users
    suspend_user = list(
        User.objects.filter(profile__suspension_time__gte=timezone.now()))
    suspended_children = list(
        Child.objects.filter(suspension_time__gte=timezone.now()))
    # for user in user_profile:
    #     if user.suspension_time >= timezone.now():
    #         suspend_user.append(user)
    # suspend_user.sort(
    #     key=lambda r: r.suspension_time)  # filter by time left and keeping track of the time user has been suspended.
    context = {
        'suspend_user': suspend_user,
        'suspended_children': suspended_children
    }
    return render(request, 'Preschool_Play/filter-suspension.html', context)
Exemplo n.º 25
0
def create_expense(title, amount, days):
    """
    Factory method to create an expense with a datetime.
    """
    time = timezone.now() - datetime.timedelta(days=days)
    return Expense.objects.create(title=title,
                                  amount=amount,
                                  transaction_date=time)
Exemplo n.º 26
0
def create_schedule_flight():
    for f in Flight.objects.all():
        t_delta = timedelta(hours=randint(-70, 70), minutes=randint(0, 60))
        ScheduleFlight.objects.create(
            time_of_departure=timezone.now() + t_delta,
            status=choice(
                [val for val, label in SCHEDULE_FLIGHT_STATUS_CHOICES]),
            flight=f)
Exemplo n.º 27
0
 def test_was_published_recently_with_old_question(self):
     """
     was_published_recently() returns False for questions whose pub_date
     is older than 1 day.
     """
     time = timezone.now() - datetime.timedelta(days=1, seconds=1)
     old_question = Question(pub_date=time)
     self.assertIs(old_question.was_published_recently(), False)
Exemplo n.º 28
0
    def destroy(self, request, *args, **kwargs) -> Response:
        registration: event_models.Registration = self.participant_initialization(
            request)

        if registration.event.last_possible_update < timezone.now():
            request.data['deactivated'] = True
            request.data[
                'needs_confirmation'] = event_choices.ParticipantActionConfirmation.Nothing
            return super().update(request, *args, **kwargs)
        elif registration.event.registration_deadline < timezone.now():
            request.data['deactivated'] = True
            if not request.data.get('avoid_manual_check'):
                request.data[
                    'needs_confirmation'] = event_choices.ParticipantActionConfirmation.Delete
            return super().update(request, *args, **kwargs)

        return super().destroy(request, *args, **kwargs)
Exemplo n.º 29
0
def cliente_list(request):
    user = request.user
    if user.has_perm('app.administrador'):
        clientes = Cliente.objects.filter(
            published_date__lte=timezone.now()).order_by('published_date')
        return render(request, 'app/listar_clientes.html', {'clientes': clientes})
    else:
        return render(request, 'app/menu.html')
Exemplo n.º 30
0
    def create(self, request, *args, **kwargs) -> Response:
        registration: event_models.Registration = self.participant_group_initialization(
            request)
        number: int = request.data.get('number', 0)
        existing_participants: QuerySet = event_models.RegistrationParticipant.objects.filter(
            registration=registration.id)
        active_participants: QuerySet = existing_participants.filter(
            deactivated=False)
        inactive_participants: QuerySet = existing_participants.filter(
            deactivated=True)
        active_participant_count: int = active_participants.count()
        inactive_participant_count: int = inactive_participants.count()
        total_participant_count: int = active_participant_count + inactive_participant_count
        activate = min(inactive_participant_count, number)
        create: int = max(number - total_participant_count, 0)
        confirm_needed: bool = registration.event.registration_deadline < timezone.now(
        )

        if activate > 0:

            if confirm_needed:
                confirm = event_choices.ParticipantActionConfirmation.AddFromExisting
            else:
                confirm = event_choices.ParticipantActionConfirmation.Nothing

            event_models.RegistrationParticipant.objects \
                .filter(pk__in=inactive_participants.order_by('created_at').values_list('pk', flat=True)[:activate]) \
                .update(deactivated=False, needs_confirmation=confirm)

        if create > 0:
            new_participants = []

            if confirm_needed:
                confirm = event_choices.ParticipantActionConfirmation.AddCompletyNew
            else:
                confirm = event_choices.ParticipantActionConfirmation.Nothing

            booking: event_models.BookingOption = registration.event.bookingoption_set.first(
            ).id

            for i in range(total_participant_count + 1, number + 1):
                participant = event_models.RegistrationParticipant(
                    first_name='Teilnehmer',
                    last_name=i,
                    registration=registration,
                    generated=True,
                    needs_confirmation=confirm,
                    booking_option=booking)
                new_participants.append(participant)
            event_models.RegistrationParticipant.objects.bulk_create(
                new_participants)

        return Response({
            'activated': activate,
            'created': create
        },
                        status=status.HTTP_201_CREATED)
Exemplo n.º 31
0
    def test_detail_rater_return_new_rating(self):
        test_user = User.objects.create_user('test', '*****@*****.**', 'pass')
        test_user.save()
        time = timezone.now()
        rating = Rating(rater=1, movie=3, rating=5, timestamp=time)
        rating.save()

        response = self.client.get(reverse('detail_rater', args=[rater.id]))
        self.assertContains(response, 'Testing')
Exemplo n.º 32
0
def interesado_create(request):
    if request.method == 'POST':
        form = InteresadosForm(request.POST)
        if form.is_valid():
            interesados = Interesados (
                nombres = form.cleaned_data['nombre'],
                apellidoPaterno = form.cleaned_data['apellido'],
                email = form.cleaned_data['email'],
                telefono = form.cleaned_data['telefono'],
                extension = form.cleaned_data['extension'],
                celular = form.cleaned_data['celular'],
                fecha = timezone.now())
            interesados.save()
            return render_to_response('micSitCeg/gracias.html', {}, content_type="text/html")
        else:
            #form =InteresadosForm()
            #return render_to_response('micSitCeg/index.html', {},  content_type="text/html")
            return redirect('/micrositios/')
    else:
        return redirect('/micrositios/nopost')
Exemplo n.º 33
0
	def check(self):
		from datetime import datetime, timezone
		from django.utils import timezone
		from timetable.utils import utc_to_local
		now = utc_to_local(timezone.now())

		actives_games = Game.objects.all().filter(is_completed = False)
		for game in actives_games:
			last_step = Step.objects.filter(game = game).latest('id')
			print(now, last_step.date)
			step_time = last_step.date
			time_delta = now - step_time
			print(time_delta)
			print(time_delta.seconds)

			delta_hours = math.floor(time_delta.seconds / 3600)
			print(delta_hours)
			if (delta_hours >= 1):
				for i in range(0, delta_hours):
					print('шаг #', i)
					self.step(game)
Exemplo n.º 34
0
def stato_riserva(riserva):
    ATTUALE = 'Attuale'
    PASSATA = 'Passata'
    # Se la riserva non è iniziata ne passata allora non mostriamo niente fino alla sua attivazione
    NON_ATTIVA = ''

    oggi = timezone.now()

    # La riserva no ha una fine è in stato indeterminato
    if not riserva.fine:
        return ATTUALE

    # se il giorno odierno e compreso tra inizio e fine delle riserve, questa è attuale
    if riserva.inizio <= oggi <= riserva.fine:
        return ATTUALE
    # se il giorno odierno è maggiore della fine riserva, questa è passata
    elif oggi > riserva.fine:
        return PASSATA
    # se il giorno di inizio della riserva è maggiore del giorno odierno, questa non è ancora attiva
    elif riserva.inizio > oggi:
        return NON_ATTIVA
Exemplo n.º 35
0
 def test_was_published_recently_with_recent_question(self):
     time = timezone.now() - datetime.timedelta(hours=1)
     recent_question = Question(pub_date=time)
     self.assertEqual(recent_question.was_published_recently(), True)
Exemplo n.º 36
0
def contact(request):
    if request.user.groups.filter(name='Students'):
        if request.method == 'POST':
            form = ContactForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                request = Request.objects.create_request(request.certificate_id , request.user.mysiteprofile.group, request.user.last_name, request.user.first_name, request.user.mysiteprofile.father_name, cd, timezone.now())
                request.save()
            return HttpResponseRedirect('/practiceapp/thanks/')
            #return render_to_response('practiceapp/contact_form.html', {'form': form})
        else:
            form = ContactForm(
            )
        return render_to_response('practiceapp/contact_form.html', {'form': form})
    else:
        return render(request, 'registration/login.html')
Exemplo n.º 37
0
 def age(self):
     return (timezone.now() - self.creation_date).days
Exemplo n.º 38
0
 def valido(self):
     from django.utils import timezone
     return timezone.now() <= (self.creazione + timedelta(hours=self.valido_ore))
Exemplo n.º 39
0
def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)
Exemplo n.º 40
0
 def create_request(self, certificate, group, name, surname, father_name, amount):
     request = self.create(certificate=certificate, group=group, name=name, surname=surname, father_name=father_name, amount=amount, pub_date= timezone.now())
     return request
Exemplo n.º 41
0
 def test_was_published_recently_with_old_question(self):
     time = timezone.now() - datetime.timedelta(days=30)
     old_question = Question(pub_date=time)
     self.assertEqual(old_question.was_published_recently(), False)
Exemplo n.º 42
0
 def was_published(self):
     #before unittest 
     #return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
     
     return timezone.now() - datetime.timedelta(days=1) <= self.pub_date <= timezone.now()
Exemplo n.º 43
0
    def test_was_recently_published_future_rating(self):
        time = timezone.now() + datetime.timedelta(days=10)
        rating = Rating(rater=2, movie=44, rating=5, timestamp=time)

        self.assertFalse(rating.was_published_recently(), "Rating not recent")