예제 #1
0
def _generate_events(semesters, subjects):
    events = []
    for i in range(random.randint(10, 20)):
        event = tutors.models.Event.objects.create(
            semester=random.choice(semesters),
            name=f"Event {i}",
            name_en=f"Event {i}",
            name_de=f"Event {i}",
            description_en=lorem.paragraph(),
            description_de=lorem.paragraph(),
            begin=django.utils.timezone.make_aware(
                datetime.today().replace(day=1, month=1)
                + timedelta(days=random.randint(0, 30), minutes=random.randint(1, 1000)),
            ),
            end=django.utils.timezone.make_aware(
                datetime.today().replace(day=1, month=12)
                - timedelta(days=random.randint(0, 30), minutes=random.randint(1, 1000)),
            ),
            meeting_point_en=lorem.sentence(),
            meeting_point_de=lorem.sentence(),
        )
        filtered_subjects = random.sample(subjects, random.randint(0, len(subjects)))
        event.subjects.set(filtered_subjects)
        event.save()
        events.append(event)

    return events
예제 #2
0
def dashboard_view(request):
    user = request.user
    notes = Note.objects.filter(author=user)[:5].reverse()
    events = CalendarEvent.objects.filter(
        Q(start_date__gte=datetime.today()) | Q(start_date__lte=datetime.today() + timedelta(days=7)),
        author=user).order_by('start_date')[:5]
    return render(request, "organiser_app/dashboard.html", {"notes": notes, "events": events})
예제 #3
0
    def handle(self, *args, **options):
        fourdaysago = datetime.today() - timedelta(days=4)
        self.stdout.write('Checking reminders...')
        reminders = models.Application.objects.filter(
            invitation_date__lte=fourdaysago,
            status=models.APP_INVITED,
            last_reminder=None)
        self.stdout.write('Checking reminders...%s found' % reminders.count())
        self.stdout.write('Sending reminders...')

        count = len([app.send_last_reminder() for app in reminders])
        self.stdout.write(
            self.style.SUCCESS(
                'Sending reminders...Successfully sent %s reminders' % count))

        onedayago = datetime.today() - timedelta(days=1)
        self.stdout.write('Checking expired...')
        expired = models.Application.objects.filter(
            last_reminder__lte=onedayago, status=models.APP_INVITED)
        self.stdout.write('Checking expired...%s found' % expired.count())
        self.stdout.write('Setting expired...')
        count = len([app.expire() for app in expired])
        self.stdout.write(
            self.style.SUCCESS(
                'Setting expired...Successfully expired %s applications' %
                count))
예제 #4
0
파일: views.py 프로젝트: gruizmir/trueque
 def show_mail_compose(self, request):
     try:
         if request.is_ajax():
             mail_sent_complete = False
             if request.method == 'POST':
                 form = ComposeMailForm(request.POST)
                 if form.is_valid():
                     new_mail = Message()
                     user = request.user
                     new_mail.id_sender = user
                     user2 = User.objects.get(id= form.cleaned_data['user_id'])
                     new_mail.id_receiver = user2
                     new_mail.datetime = datetime.now()
                     new_mail.id_conversation = 1
                     new_mail.text = form.cleaned_data['text']
                     new_mail.subject = form.cleaned_data['subject']
                     new_mail.save()
                     form = ComposeMailForm()
                     mail_sent_complete = MAILSENTCOMPLETE
             else: 
                 form = ComposeMailForm()
             week = {0:'Lunes',1:'Martes',2:'Miércoles',3:'Jueves',4:'Viernes',5:'Sábado',6:'Domingo'}
             month = {0: 'Enero', 1:'Febrero',2:'Marzo',3:'Abril',4:'Mayo',5:'Junio',6:'Julio',7:'Agosto',8:'Septiembre',9:'Octubre',10:'Noviembre',11:'Diciembre'}
             date_time = week[datetime.today().weekday()] + " " + str(datetime.today().day) + "/" + month[datetime.today().month - 1] + " " + str(datetime.today().year)
             c = { 'form': form , 'date_t':date_time, 'mail_sent_complete' : mail_sent_complete}
             c.update(csrf(request))
             return render_to_response('user_send_mail.html', c)
         else: return HttpResponseRedirect("/usuarios/profile/mail")
         
     except Exception as e: return self.show_error(e)
예제 #5
0
    def testCreatePieceExtraData(self):
        user = self.user1

        save_piece = Piece(title='title',
                           artist_name='artist_name',
                           date_created=datetime.today().date(),
                           extra_data={'extra_data_string': 'something'},
                           num_editions=2,
                           user_registered=user,
                           digital_work=self.digitalwork_user1)
        save_piece.save()

        find_piece = Piece.objects.get(id=save_piece.id)
        self.assertTrue(save_piece == find_piece)

        self.assertNotEqual(save_piece.digital_work, None)
        self.assertEqual(len(find_piece.extra_data), 1)

        save_piece = Piece(title='title',
                           artist_name='artist_name',
                           date_created=datetime.today().date(),
                           num_editions=2,
                           user_registered=user,
                           digital_work=self.digitalwork_user1)
        save_piece.save()
        find_piece = Piece.objects.get(id=save_piece.id)
        self.assertTrue(save_piece == find_piece)
        self.assertEqual(find_piece.extra_data, {})
예제 #6
0
def _generate_fahrt_data():
    return fahrt.models.Fahrt.objects.create(
        semester=settool_common.models.current_semester(),
        date=django.utils.timezone.make_aware(datetime.today() + timedelta(days=20)),
        open_registration=django.utils.timezone.make_aware(datetime.today() - timedelta(days=20)),
        close_registration=django.utils.timezone.make_aware(datetime.today() + timedelta(days=1)),
    )
예제 #7
0
class faltesAssistenciaEntreDatesForm(forms.Form):

    grup = forms.ModelChoiceField(queryset=None)
    assignatura = forms.ModelMultipleChoiceField(queryset=None)
    dataDesDe = forms.DateField(help_text=u'Data on començar a comptar',
                                initial=datetime.today(),
                                required=True,
                                widget=DateTextImput())
    horaDesDe = forms.ModelChoiceField(queryset=None, initial=None)
    dataFinsA = forms.DateField(help_text=u'Data on començar a comptar',
                                initial=datetime.today(),
                                required=True,
                                widget=DateTextImput())
    horaFinsA = forms.ModelChoiceField(queryset=None, initial=None)

    def __init__(self, *args, **kwargs):
        self.assignatures = kwargs.pop('assignatures', None)
        self.grups = kwargs.pop('grups', None)
        super(faltesAssistenciaEntreDatesForm, self).__init__(*args, **kwargs)
        self.fields['assignatura'].queryset = self.assignatures
        self.fields['grup'].queryset = self.grups
        self.fields['horaDesDe'].queryset = FranjaHoraria.objects.all()
        self.fields['horaDesDe'].initial = [FranjaHoraria.objects.all()[0]]
        self.fields['horaFinsA'].queryset = FranjaHoraria.objects.all()
        self.fields['horaFinsA'].initial = [FranjaHoraria.objects.reverse()[0]]
예제 #8
0
    def save(self, *args, **kwargs):
        if str(self.date) > str(datetime.today().date()):
            raise Exception("The date should not be in the future!")
        if str(self.date) == str(datetime.today().date()) and str(
                self.time) > str(datetime.today().time()):
            raise Exception("The time should not be in the future!")

        super(Meal, self).save(*args, **kwargs)
예제 #9
0
    def filter(self, qs, value):
        queryset = qs

        if value is True:
            queryset = queryset.filter(end_date__lt=datetime.today())

        elif value is False:
            queryset = queryset.exclude(end_date__lt=datetime.today())

        return queryset
예제 #10
0
    def subscribed_today(self, obj):
        try:
            created = obj.created_at.date()
        except:
            created = obj.created_at

        print "%s = %s = %s" % (created,
                                datetime.today(),
                                timezone.now())
        return created == datetime.today().date()
예제 #11
0
 def get_recent_previous_launches(self, offset=0):
     """
     Sends a request using `requests` module.
     :return: Returns a HTTP Response object
     """
     today = (datetime.today() + timedelta(days=1)).strftime('%Y-%m-%d')
     previous = (datetime.today() - timedelta(days=2)).strftime('%Y-%m-%d')
     url = self.api_url + '/launch/%s/%s?mode=verbose&offset=%s&limit=100' % (
         previous, today, offset)
     return send_request(url, method='GET', headers=headers)
예제 #12
0
def _generate_tasks_tutorasignemt(
    events,
    tutors_list,
    questions,
):
    tasks = []
    for event in events:
        tutors_current_semester = [tutor for tutor in tutors_list if tutor.semester == event.semester]
        number1 = random.randint(0, len(tutors_current_semester))
        number2 = random.randint(0, len(tutors_current_semester))
        filtered_questions = [question for question in questions if question.semester == event.semester]
        event_subjects = list(event.subjects.all())
        for i in range(0, random.randint(0, 4)):
            task = tutors.models.Task.objects.create(
                semester=event.semester,
                name_en=f"Task {i}",
                name_de=f"Task {i}",
                description_en=lorem.paragraph(),
                description_de=lorem.paragraph(),
                begin=django.utils.timezone.make_aware(
                    datetime.today().replace(day=1, month=1)
                    + timedelta(days=random.randint(0, 30), minutes=random.randint(1, 1000)),
                ),
                end=django.utils.timezone.make_aware(
                    datetime.today().replace(day=1, month=12)
                    - timedelta(days=random.randint(0, 30), minutes=random.randint(1, 1000)),
                ),
                meeting_point_en=lorem.sentence()[: random.randint(0, 49)],
                meeting_point_de=lorem.sentence()[: random.randint(0, 49)],
                event=event,
                min_tutors=min(number1, number2),
                max_tutors=max(number1, number2),
            )
            task.requirements.set(
                random.sample(filtered_questions, random.randint(0, len(filtered_questions))),
            )
            task.allowed_subjects.set(
                random.sample(event_subjects, random.randint(0, len(event_subjects))),
            )
            tutors_for_task = random.sample(
                tutors_current_semester,
                random.randint(min(number1, number2), max(number1, number2)),
            )
            for tutor in tutors_for_task:
                tutors.models.TutorAssignment.objects.create(
                    task=task,
                    tutor=tutor,
                )

            task.save()
            tasks.append(task)
    return tasks
예제 #13
0
def _generate_fahrt_participants(
    common_subjects,
    fahrt_data,
):
    fahrt_participants = []
    for i in range(60):
        fahrt_participants.append(
            fahrt.models.Participant.objects.create(
                semester=fahrt_data.semester,
                gender=random.choice(fahrt.models.Participant.GENDER_CHOICES)[0],
                firstname=f"Firstname {i}",
                surname=f"Lastname {i}",
                birthday=generate_random_birthday(),
                email=f"{i}@test.com",
                phone=f"+49 89 {i:07d}",
                mobile=f"+49 176 {i:07d}",
                subject=random.choice(common_subjects),
                nutrition=random.choice(("normal", "vegeterian", "vegan")),
                allergies=random.choice(("gute Noten", "sport", "spargel"))
                if random.choice((True, False, False, False, False))
                else "",
                publish_contact_to_other_paricipants=random.choice((True, True, False)),
                non_liability=django.utils.timezone.make_aware(
                    datetime.today() - timedelta(random.randint(0, 4)),
                )
                if random.choice((True, True, False))
                else None,
                paid=django.utils.timezone.make_aware(
                    datetime.today() - timedelta(random.randint(0, 4)),
                )
                if random.choice((True, True, False))
                else None,
                payment_deadline=django.utils.timezone.make_aware(
                    datetime.today() + timedelta(random.randint(0, 10)),
                )
                if random.choice((True, True, True, False))
                else None,
                status=random.choice(
                    (
                        "registered",
                        "confirmed",
                        "registered",
                        "confirmed",
                        "waitinglist",
                        "cancelled",
                    ),
                ),
                mailinglist=random.choice((False, False, False, True)),
                comment=lorem.sentence() if random.choice((False, False, False, True)) else "",
            ),
        )
    return fahrt_participants
예제 #14
0
    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.created = datetime.today()
            self.percent_update_time = datetime.today()
        else:
            old_task = Task.objects.get(id=self.id)
            if self.percent_complete != old_task.percent_complete:
                self.previous_percent_complete = old_task.percent_complete
            else:
                self.percent_update_time = datetime.today()
        self.modified = datetime.today()

        super(Task, self).save(*args, **kwargs)
예제 #15
0
class alertaAssistenciaForm(forms.Form):
    data_inici = forms.DateField(label=u'Data inici',
                                 initial=datetime.today(),
                                 required=True,
                                 help_text=u'Dia inicial pel càlcul',
                                 widget=DateTextImput())

    data_fi = forms.DateField(label=u'Data fi',
                              initial=datetime.today(),
                              required=True,
                              help_text=u'Dia final pel càlcul',
                              widget=DateTextImput())

    tpc = forms.IntegerField(
        label=u'filtre %',
        max_value=100,
        min_value=1,
        initial=25,
        help_text=
        u'''Filtra alumnes amb % de absència superior a aquet valor.''',
        widget=TextInput(attrs={'class': "slider"}))

    nivell = forms.ModelChoiceField(
        queryset=Nivell.objects.all(),
        required=True,
        empty_label=None,
    )
    ordenacio = forms.ChoiceField(
        choices=(
            (
                'a',
                u'Nom alumne',
            ),
            (
                'ca',
                u'Curs i alumne',
            ),
            (
                'n',
                u'Per % Assistència',
            ),
            (
                'cn',
                u'Per Curs i % Assistència',
            ),
        ),
        required=True,
        label=u'Ordenació',
        initial='a',
        help_text=u'Tria com vols ordenats els resultats')
예제 #16
0
def _generate_tutor_settings(common_semesters):
    all_mail_by_set_tutor = tutors.models.TutorMail.objects.all()
    for semester in common_semesters:
        if random.choice((True, True, False)):
            tutors.models.Settings.objects.create(
                semester=semester,
                open_registration=django.utils.timezone.make_aware(datetime.today() - timedelta(days=20)),
                close_registration=django.utils.timezone.make_aware(datetime.today() + timedelta(days=20)),
                mail_registration=all_mail_by_set_tutor[0],
                mail_confirmed_place=all_mail_by_set_tutor[1],
                mail_waiting_list=all_mail_by_set_tutor[2],
                mail_declined_place=all_mail_by_set_tutor[3],
                mail_task=all_mail_by_set_tutor[4],
            )
예제 #17
0
def basic_stats(request):
    setups = {
        "pre_page_name": "KOTKT",
        "alerts": SpecialDateModel.objects.filter(date_implied=datetime.today().date())
    }

    return setups
예제 #18
0
파일: views.py 프로젝트: NateRiv3r/TODOLIST
def get_date(req_month):
    if req_month:
        year = int(req_month.split('-')[0])
        month = int(req_month.split('-')[1])
        day = int(req_month.split('-')[2]) or 1
        return date(year, month, day=day)
    return datetime.today()
예제 #19
0
class complementFormulariTriaForm(forms.Form):
    dia = forms.DateField(label=u'Data Baixa',
                          initial=datetime.today(),
                          required=True,
                          help_text=u'Data de la baixa',
                          widget=DateTextImput())
    professor = forms.ModelChoiceField(queryset=Professor.objects.all())
예제 #20
0
class disponibilitatAulaPerFranjaForm(forms.Form):

    franja = forms.ModelChoiceField(queryset=FranjaHoraria.objects.all())

    data = forms.DateField(help_text="Data a consultar",
                           initial=datetime.today(),
                           required=True,
                           widget=DateTextImput())

    def clean(self):
        cleaned_data = super(disponibilitatAulaPerFranjaForm, self).clean()

        data = self.cleaned_data['data']
        tretze_dies = timedelta(days=13)
        darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta(
            days=datetime.today().weekday())
        if data > darrer_dia_reserva or data < datetime.today().date():
            raise forms.ValidationError(
                u"Només pots reservar a partir d'avui i fins al dia {0}".
                format(darrer_dia_reserva))

        franja = self.cleaned_data['franja']
        franges_del_dia = (FranjaHoraria.objects.filter(
            horari__impartir__dia_impartir=data).order_by('hora_inici'))
        primera_franja = franges_del_dia.first()
        darrera_franja = franges_del_dia.last()
        if franja.hora_inici < primera_franja.hora_inici or franja.hora_fi > darrera_franja.hora_fi:
            raise forms.ValidationError(
                u"En aquesta franja i dia no hi ha docència")

        return cleaned_data
예제 #21
0
파일: api.py 프로젝트: skurt23/Welldone
    def get_queryset(self):


        blogs = Article.objects.all().select_related("owner").order_by('-publicated_at')

        if self.request.user.is_superuser:
            # como administrador obtiene todos los posts.
            return blogs
        elif self.request.user.is_authenticated():
            # no obtiene los posts que esten privados de otros usuarios. y solo los publicados hasta al dia de hoy.
            blogs = blogs.filter(publicated_at__lte=datetime.today())
            return blogs.exclude(Q(visibility=VISIBILITY_PRIVATE) & ~Q(owner=self.request.user))

        else:
            # invitado prodra ver los posts publicos.
            return blogs.filter(publicated_at__lte=datetime.today(), visibility=VISIBILITY_PUBLIC)
예제 #22
0
def notify_not_downloaded(person_intensions, current_template, reminder=False):
    logger.info("Notyfying not downloaded.")
    subject_ext = ""
    for pi in person_intensions:
        if pi.person.active and not pi.downloaded:
            lang = pi.person.language
            logger.info("Activating language %s and reminder %s" %
                        (lang, reminder))
            translation.activate(lang)
            if reminder:
                subject_ext = _(" - reminder")
            if not current_template:
                template = _(
                    "God bless,\n Under the link \n%s\nthere is a new Live Rosary mystery.\n Pease report any problems with downloading or opening the file to [email protected] email address.\nSincerely\nCyberarche Team"
                )
            else:
                template = current_template
            url = settings.LOCATION_TEMPLATE % pi.code
            email = pi.person.email
            message = template % url
            month = datetime.today().strftime('%m-%Y')
            subject = _("LR mystery for %(month)s%(subject_ext)s") % {
                'month': month,
                'subject_ext': subject_ext
            }
            send_mail(subject, message, "*****@*****.**", email)
            logger.info("Send email to %s with code %s and body %s" %
                        (email, pi.code, message))
예제 #23
0
def create_tutor_fixture_state():
    course_bundle_mathe = CourseBundle.objects.create(name="Mathe", name_de="Mathematics", name_en="Mathematik")
    course_bundle_info = CourseBundle.objects.create(name="Info", name_de="Informatics", name_en="Informatik")
    subject1 = Subject.objects.create(
        degree=Subject.BACHELOR,
        subject="Info",
        subject_de="Informathik",
        subject_en="Informathics",
        course_bundle=course_bundle_info,
    )
    subject2 = Subject.objects.create(
        degree=Subject.MASTER,
        subject="Mathe",
        subject_de="Mathemathik",
        subject_en="mathemathics",
        course_bundle=course_bundle_mathe,
    )
    semester1, semester2 = generate_semesters()

    for i in range(20):
        tutor = Tutor(  # nosec: this is a fixture
            semester=semester1 if i % 2 == 0 else semester2,
            first_name=f"Firstname_{i}",
            last_name=f"Lastname_{i}",
            email=f"{i}@test.com",
            subject=subject1 if random.randint(0, 1) == 0 else subject2,
            tshirt_size=Tutor.TSHIRT_SIZES[i % len(Tutor.TSHIRT_SIZES)][0],
            tshirt_girls_cut=random.randint(0, 1) == 0,
            status=Tutor.STATUS_ACCEPTED if i >= 5 else Tutor.STATUS_DECLINED,
            matriculation_number=f"{i:02d}",
            birthday=datetime.today(),
        )
        tutor.save()
예제 #24
0
    def subscribed_today(self, obj):
        try:
            created = obj.created_at.date()
        except:
            created = obj.created_at

        return created == datetime.today().date()
예제 #25
0
class disponibilitatRecursPerFranjaForm(forms.Form):

    franja = forms.ModelChoiceField( queryset = FranjaHoraria.objects.all()  )

    data = forms.DateField(help_text="Data a consultar",
                                initial=datetime.today(),
                                required=True,
                                widget=DateTextImput())

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(disponibilitatRecursPerFranjaForm, self).clean()

        data=self.cleaned_data['data']
        tretze_dies = timedelta(days=13)
        darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta(days=datetime.today().weekday())
        es_reservador = User.objects.filter(pk=self.user.pk, groups__name__in=['reservador']).exists()
        if not es_reservador and (data > darrer_dia_reserva or data < datetime.today().date()):
            raise forms.ValidationError(u"Només pots reservar a partir d'avui i fins al dia {0}".format(darrer_dia_reserva))

        franja = self.cleaned_data['franja']
        franges_del_dia = (FranjaHoraria
                           .objects
                           .filter(horari__impartir__dia_impartir=data)
                           .order_by('hora_inici')
                           )
        primera_franja = franges_del_dia.first()
        darrera_franja = franges_del_dia.last()
        if franja.hora_inici < primera_franja.hora_inici or franja.hora_fi > darrera_franja.hora_fi:
            raise forms.ValidationError(u"En aquesta franja i dia no hi ha docència")

        return cleaned_data
def test_StrictDateTimeField_ok_until_changed():
    """
    Ensure this value cannot change to an invalid state after being set
    """
    model = DateTimeFieldModel(field=datetime.today())
    with pytest.raises(ValidationError):
        model.field = '2000-00-00'
def test_StrictDateTimeField_form_with_instance_invalid():
    today = datetime.today()
    x = DateTimeFieldModel(field=today)
    form_class = modelform_factory(model=DateTimeFieldModel, fields=['field'])
    form = form_class(data={'field': 9223372036854775808}, instance=x)
    assert form.is_valid() is False
    assert form.errors == {'field': ['Enter a valid date/time.']}
def test_StrictDateTimeField_form_without_instance_valid():
    today = datetime.today()
    form_class = modelform_factory(model=DateTimeFieldModel, fields=['field'])
    form = form_class(data={'field': today})
    assert form.is_valid() is True
    assert form.errors == {}
    assert form.save().field == today
예제 #29
0
class passaLlistaGrupDataForm(forms.Form):
    grup = forms.ModelChoiceField(queryset=Grup.objects.filter(
        alumne__isnull=False).distinct().order_by("descripcio_grup"))
    dia = forms.DateField(label=u'Dia',
                          initial=datetime.today(),
                          help_text=u'Dia a passar llista.',
                          widget=DateTextImput())
예제 #30
0
    def get_context_data(self, **kwargs):
        context = super(RecordingsGrowth, self).get_context_data(**kwargs)

        all_recordings = core_models.AudioData.objects.all().order_by(
            'created')

        recordings_count = []
        labels = []
        datas = []
        initial_date = all_recordings[0].created
        date = initial_date
        days_to_group = self.request.GET.get("days", 7)
        while date < timezone.make_aware(datetime.today(),
                                         timezone.get_default_timezone()):
            new_date = date + timedelta(days=days_to_group)
            date_element = dict()
            date_element['date'] = new_date
            date_element['count'] = all_recordings.filter(
                created__range=[initial_date, new_date]).count()
            recordings_count.append(date_element)
            labels.append(date_element['date'])
            datas.append(date_element['count'])
            date = new_date

        context['recordings_count'] = recordings_count
        context['labels'] = labels
        context['datas'] = datas

        return context
예제 #31
0
파일: forms.py 프로젝트: DiMaksimov/DB2
class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation',
                                widget=forms.PasswordInput)

    date_of_birth = forms.DateField(
        widget=forms.SelectDateWidget(years=range(datetime.today().year -
                                                  1, 1939, -1), ))

    class Meta:
        model = DB2User
        fields = ('email', 'date_of_birth', 'country', 'city')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
예제 #32
0
class Experience(models.Model):
    user_name=models.ForeignKey(User,on_delete=models.CASCADE)
    company_name=models.ForeignKey(Company,on_delete=models.CASCADE)
    #sal=models.OneToOneField(User,on_delete=models.CASCADE)

    salary=models.FloatField()
    designation=models.CharField(max_length=30)
    currrently_working=models.BooleanField()
    hire_date=models.DateField()
    end_date =models.DateField()
    date_now= datetime.today().date()

    # def clean(self):
    #     if self.end_date < self.hire_date:
    #         msg = u"End date should be greater than start date."
    #         raise ValidationError(msg)
    #     if self.end_date>self.date_now:
    #         msg = u"End date should not be greater than start date."
    #         raise ValidationError(msg)



    def __str__(self):
            return '{} {}  {}'.format(self.user_name, self.company_name,self.designation)

    class Meta:
        verbose_name_plural = "Experiencies"
예제 #33
0
def piece(alice, digital_work):
    from piece.models import Piece
    return Piece.objects.create(
        user_registered=alice,
        date_created=datetime.today().date(),
        digital_work=digital_work,
    )
예제 #34
0
    def testCreatePieceDate(self):
        user = self.user1

        save_piece = Piece(title='title',
                           artist_name='artist_name',
                           date_created=self.date,
                           extra_data={'extra_data_string': 'something'},
                           num_editions=2,
                           user_registered=user,
                           digital_work=self.digitalwork_user1)
        save_piece.save()

        find_piece = Piece.objects.get(id=save_piece.id)
        self.assertTrue(save_piece == find_piece)
        self.assertEqual(find_piece.date_created, self.date)
        self.assertGreater(datetime.today().replace(tzinfo=pytz.UTC),
                           find_piece.datetime_registered)

        save_piece = Piece(title='title',
                           artist_name='artist_name',
                           date_created=self.date,
                           extra_data={'extra_data_string': 'something'},
                           num_editions=2,
                           user_registered=user,
                           digital_work=self.digitalwork_user1)
        save_piece.save()

        find_piece = Piece.objects.get(id=save_piece.id)
        self.assertEqual(find_piece.datetime_registered.date(),
                         datetime.utcnow().replace(tzinfo=timezone.utc).date())
예제 #35
0
    def create_piece_web(self,
                         user,
                         title,
                         artist_name,
                         num_editions,
                         digital_work_key,
                         date_created=datetime.today().date().year,
                         thumbnail_file=None):
        data = {
            'title': title,
            'artist_name': artist_name,
            'num_editions': num_editions,
            'date_created': date_created,
            'digital_work_key': digital_work_key
        }
        if thumbnail_file:
            data['thumbnail_file'] = thumbnail_file

        view = PieceEndpoint.as_view({'post': 'create'})
        request = self.factory.post('/api/pieces/', data)
        force_authenticate(request, user)

        response = view(request)
        self.last_request = Request(request)
        return response
예제 #36
0
class regeneraImpartirForm(forms.Form):

    data_inici = forms.DateField(
        label=u'Data regeneració',
        initial=datetime.today(),
        required=True,
        help_text=u'Data en que entra en vigor l\'horari actual',
        widget=DateTextImput())

    franja_inici = forms.ModelChoiceField(queryset=FranjaHoraria.objects.all(),
                                          required=True)

    confirma = forms.BooleanField(
        label=u'Confirma regenerar horaris',
        required=True,
        help_text=u'És un procés costos, confirma que el vols fer',
    )

    def clean_data_regeneracio(self):
        data = self.cleaned_data['data_regeneracio']
        if data < datetime.today():
            raise forms.ValidationError(
                u'Només es pot regenerar amb dates iguals o posteriors a avui.'
            )

        # Always return the cleaned data, whether you have changed it or
        # not.
        return data

    def clean_confirma(self):
        data = self.cleaned_data['confirma']
        if not data:
            raise forms.ValidationError(u'Confirma la regeneració d\'horari.')

        return data
예제 #37
0
    def clean_data_regeneracio(self):
        data = self.cleaned_data['data_regeneracio']
        if data <  datetime.today():
            raise forms.ValidationError(u'Només es pot regenerar amb dates iguals o posteriors a avui.')

        # Always return the cleaned data, whether you have changed it or
        # not.
        return data
예제 #38
0
def piece_with_thumbnail(alice, digital_work, thumbnail):
    from piece.models import Piece
    return Piece.objects.create(
        user_registered=alice,
        date_created=datetime.today().date(),
        digital_work=digital_work,
        thumbnail=thumbnail,
    )
예제 #39
0
    def hottest(self, request):
        posts = Post.get_user_view(request.user.id) \
            .filter(parent=None, created_at__gte=datetime.today() - timedelta(days=1)) \
            .order_by('-likes_count')

        serializer = PostSerializer(posts, many=True)

        return Response(serializer.data)
def test_StrictDateTimeField_update_via_queryset_invalid_then_get():
    """
    So for whatever reason, by the time this gets to the FieldCleaningDescriptor
    the 'blep' has been converted into True ... fun.
    """
    model = DateTimeFieldModel.objects.create(field=datetime.today())
    model.__class__.objects.filter(pk=model.pk).update(field='2000-01-01')
    assert model.__class__.objects.get(pk=model.pk).field == datetime(2000, 1, 1, 0, 0)
예제 #41
0
 def test_should_only_return_completed_tasks(self):
     this_month = datetime.today()
     last_month = this_month - relativedelta(months=+1)
     tasks = TaskData().create_many(4, {'completed_date': [last_month, last_month, this_month, this_month],
                                        'status': [Task.COMPLETED, Task.COMPLETED, Task.READY, Task.COMPLETED]})
     completed_task = tasks[-1]
     response = self.client.get(self.monthly_url)
     self.assertEqual(len(response.data), 1)
     self.assertEqual(response.data[0]['title'], completed_task.title)
def test_StrictDateTimeField_form_with_instance_valid():
    today = datetime.today()
    future = today + timedelta(days=2)
    x = DateTimeFieldModel(field=today)
    form_class = modelform_factory(model=DateTimeFieldModel, fields=['field'])
    form = form_class(data={'field': future}, instance=x)
    assert form.is_valid() is True
    assert form.errors == {}
    assert form.save().field == future
예제 #43
0
    def bind_to_owner(self, visitant):
        self.able_to_bind_to_owner(visitant)
        # Anoto que ha llegit el QR
        self.capturadeqrmosqueter_set.create(visitant=visitant, caduca_dia=datetime.today() + timedelta(days=15))

        self.n_lectures_restants_cache -= 1

        self.save()

        visitant.save()
예제 #44
0
 def test_should_return_a_list_of_tasks_from_the_current_month(self):
     """
     Create tasks in current and previous months and only current months tasks
     should be returned.
     """
     this_month = datetime.today()
     last_month = this_month - relativedelta(months=+1)
     tasks = TaskData().create_many(4, {'completed_date': [last_month, last_month, this_month, this_month],
                                        'status': [Task.COMPLETED] * 4})
     response = self.client.get(self.monthly_url)
     self.assertEqual(len(response.data), 2)
예제 #45
0
    def clean(self):
        cleaned_data = super(disponibilitatAulaPerFranjaForm, self).clean()

        data=self.cleaned_data['data']
        tretze_dies = timedelta(days=13)
        darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta(days=datetime.today().weekday())
        if data > darrer_dia_reserva or data < datetime.today().date():
            raise forms.ValidationError(u"Només pots reservar a partir d'avui i fins al dia {0}".format(darrer_dia_reserva))

        franja = self.cleaned_data['franja']
        franges_del_dia = (FranjaHoraria
                           .objects
                           .filter(horari__impartir__dia_impartir=data)
                           .order_by('hora_inici')
                           )
        primera_franja = franges_del_dia.first()
        darrera_franja = franges_del_dia.last()
        if franja.hora_inici < primera_franja.hora_inici or franja.hora_fi > darrera_franja.hora_fi:
            raise forms.ValidationError(u"En aquesta franja i dia no hi ha docència")

        return cleaned_data
예제 #46
0
def statistic(request):
    if request.is_ajax():
        month = request.GET.get('month')
        m = request.GET.get('number')
        n = int(m)+1
        year = str(datetime.today().year)
        from_date = '2015' + '-' + m + '-'+'1'
        until_date = year + '-' + str(n) + '-'+'1'
        data= EarthQuake.objects.filter(Origin_Time__gte=from_date, Origin_Time__lt=until_date)
        return render_to_response("graph.html", context={'data': data, 'month':month})
    else:
        return render_to_response("statistic.html")
예제 #47
0
    def bind_to_owner(self, visitant):
        self.able_bind_to_owner(visitant)
        # anoto el propietari del QR
        captura = CapturaDeQRClinex()
        captura.QRClinex = self
        captura.caduca_dia = datetime.today() + timedelta(days=15)
        captura.visitant = visitant
        captura.collaborador = self.talonari.collaborador
        captura.save()
        # self.qrclinex = captura

        # acumular punts al visitant!
        visitant.save()
예제 #48
0
def detallProfessorHorari(request, pk, detall='all'):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    #grups_poden_veure_detalls = [u"sortides",u"consergeria",u"direcció",]

    #mostra_detalls = user.groups.filter(name__in=grups_poden_veure_detalls).exists()

    data_txt = request.GET.get( 'data', '' )

    try:
        data = datetime.strptime(data_txt, r"%Y-%m-%d").date()
    except ValueError:
        data = datetime.today()


    professor = get_object_or_404( Professor, pk=pk)
    tutoria = professor.tutor_set.filter( professor = professor )

    qHorari = Q(horari__professor = professor, dia_impartir = data)
    qGuardies = Q(professor_guardia = professor, dia_impartir = data)
    imparticions = Impartir.objects.filter( qHorari | qGuardies ).order_by( 'horari__hora')

    table=HorariProfessorTable(imparticions)

    RequestConfig(request).configure(table)

    return render(
        request,
        'mostraInfoProfessorCercat.html',
        {'table': table,
         'professor':professor,
         'tutoria': tutoria,
         'dia' : data,
         'lendema': (data + timedelta( days = +1 )).strftime(r'%Y-%m-%d'),
         'avui': datetime.today().date().strftime(r'%Y-%m-%d'),
         'diaabans': (data + timedelta( days = -1 )).strftime(r'%Y-%m-%d'),
         })
예제 #49
0
def returns_templateresponse(request):
    return TemplateResponse(request, template="admin/base.html", context={
        'form': Form(),
        # 'queryset': get_user_model().objects.all(),
        'model': get_user_model()(),
        'thing': 1,
        'dt': datetime.today(),
        'sub': {
            'sub2': {
                'yay': 1,
                'woo': 'heh',
            }
        }
    })
예제 #50
0
def load_main_page(request):
    today = datetime.today().date()
    eq_pos = EarthQuake.objects.filter(Origin_Time__contains=today)
    if request.GET.get("eq"):
        eq = request.GET.get("eq")
        return show_eq_details(request, eq)
    # elif request.is_ajax():
    #     content = request.GET.get('content')
    #     if content == "map":
    #         return HttpResponse("<script>window.location.replace('http://127.0.0.1:8000/');</script>")
    #     elif content == "report":
    #         is_filter = False
    #         return state_report(request, is_filter)
    #     elif content == "statistic":
    #         pass
    return render_to_response('MainPage.html', {'content': "map", 'eq_pos': eq_pos})
예제 #51
0
파일: utils.py 프로젝트: JaumeI/django-aula
def fact_controls_dissociats( n=-1 ): 
    debug = n
    file_name = os.path.join( settings.BI_DIR, 'controls_dissociats.csv')
    ofile = open(file_name, 'wb')
    writer = csv.writer(ofile)
    
    element_row = []
    
    columnes = [    
             'nom_nivell' ,
             'hora_inici' ,
             'assistenciaMateixaHora1WeekBefore' ,
             'assistenciaMateixaHora2WeekBefore' ,
             'assistenciaMateixaHora3WeekBefore' ,
             'assistenciaaHoraAnterior' ,
             'assistencia' ]
    for c in columnes:
        element_row.append( c )
    writer.writerow( element_row ) 
 
    pks =  ( ControlAssistencia
             .objects
             .exclude( alumne__data_baixa__isnull = False )
             .filter(
                   impartir__dia_impartir__lt =  datetime.today(),
                   impartir__dia_impartir__gt =  date( year = 2012, month = 10, day = 1 )  
                       )
             .values_list('id', flat=True)
             .order_by( 'impartir__dia_impartir' )
            )
    
    for pk in pks:
        element = ControlAssistencia.objects.get( pk = pk )
        debug -= 1
        if debug == 0:
            break

        row = []
            
        dades = dades_dissociades(element) 
        for c in columnes:
            row.append( dades[c] )
        writer.writerow( row ) 
    
    ofile.close()
def test_StrictDateTimeField_descriptor_doesnt_disappear():
    """
    don't clobber the descriptor
    """
    today = datetime.today()
    value = DateTimeFieldModel(field=today)
    assert value.field == today
    value.field = '2015-04-16'
    assert value.field == datetime(2015, 4, 16, 0, 0)
    with pytest.raises(ValidationError):
        value.field = 'v'*256
    assert value.field == datetime(2015, 4, 16, 0, 0)
    value.field = today
    assert value.field == today
    with pytest.raises(TypeError):
        value.field = -1
    with pytest.raises(ValidationError):
        value.field = '-1'
예제 #53
0
def state_report(request, is_filter=True):
    report = EarthQuake.objects.filter(Origin_Time__contains=datetime.date(datetime.today()))
    if request.is_ajax():
        query = Q()
        if request.POST.get('state'):
            state = request.POST.get('state')
            query &= (Q(Region__icontains=state))
        if request.POST.get('magnitude'):
            magnitude = request.POST.get('magnitude')
            query &= (Q(Magnitude=magnitude))
        if request.POST.get('fdate'):
            from_date = request.POST.get('fdate')
            query &= (Q( Origin_Time__gte=from_date))
        if request.POST.get('tdate'):
            to_date = request.POST.get('tdate')
            query &= (Q(Origin_Time__lte=to_date))
        report = EarthQuake.objects.filter(query)
        global whatToShow
    whatToShow = report
    return render(request, 'Report.html', {'earthquakes': report.reverse(), 'content':"report"})
예제 #54
0
def _get_dispatched_warning(request):
    if not request.user.is_authenticated():
        return
    if not request.user.get_profile().is_seller:
        return
    awaiting_shipping = request.user.stall.orders.awaiting_shipping()
    awaiting_shipping_overdue = awaiting_shipping.filter(
        created__lt=datetime.today() + timedelta(days=3))
    warning_msg = (
        'Look out {name}! You have order(s) that have not been '
        'marked as dispatched or refunded and this will be causing problems '
        'for customers or delays in getting you paid. <a href="{url}">Fix '
        'this now</a>, or <a href="{help_url}" target="_blank">get some help on this</a>.'
        if awaiting_shipping_overdue.count() > 0 else
        '{name}, just a reminder that you have orders to mark as dispatched '
        'or refunded. Please <a href="{url}">do so here</a> or '
        '<a href="{help_url}" target="_blank">get some help</a>.'
        if awaiting_shipping.count() > 0 else ""
    )
    return mark_safe(warning_msg.format(
        name=request.user.first_name, url=reverse("sold"),
        help_url="http://help.ecomarket.com/customer/portal/articles/828639"))
예제 #55
0
파일: views.py 프로젝트: jolu7432/Seminario
def server(request):
    msg = ""
    if 'token' in request.GET and request.GET['token'] == "1234":
        ip = get_ip(request)
        if ip is not None and Silo.objects.filter(ip_asignada=ip).exists():
            si = Silo.objects.get(ip_asignada=ip)
            queryset = Sensor.objects.filter(silo=si)
            fecha = datetime.today()
            datos = ""
            for item in queryset:
                i = item.identificador
                alerta = Alerta()
                alerta.tiempo = fecha
                if 't' + `i` in request.GET and request.GET['t' + `i`] is not None:
                    alerta.temperatura = float(request.GET['t' + `i`])
                else:
                    alerta.temperatura = 0
                if 'h' + `i` in request.GET and request.GET['h' + `i`] is not None:
                    alerta.humedad = float(request.GET['h' + `i`])
                else:
                    alerta.humedad = 0
                alerta.sensor = item
                if request.GET['alerta'] == "0":
                    alerta.es_alerta = False
                else:
                    alerta.es_alerta = True
                alerta.save()
                datos += 't' + `i` + "= " + `alerta.temperatura`
                datos += ' h' + `i` + "= " + `alerta.humedad` + " "
            if request.GET['alerta'] == "1":
                to = Puesto.objects.filter(silo=si)
                for t in to:
                    email = EmailMessage("Se produjo alerta en Arduino",
                                         "Se ha producido un alerta en el Silo: Ip=" + si.ip_asignada + ". Ubicacion= " + si.ubicacion + ". Datos Sensores: " + datos,
                                         to=[t.user.email])
                    email.send()
            msg = "Guardado Correcto."
예제 #56
0
파일: admin.py 프로젝트: renatocan/eventex
 def subscribed_today(self, obj):
     return obj.created_at.date() == datetime.today().date()
예제 #57
0
 def cadastrado_hoje(self, obj):
     return obj.criado_em.date() == datetime.today().date()
예제 #58
0
def canvas_obiettivo_trimestrale(request):
    template = TMP_CANVAS
    
    # FIXME: ragionare sulla gestione del periodo
    if request.method == "GET" and request.GET.has_key("fanno") and request.GET.has_key("fquarto"):
        period = u.get_quarter(request.GET)
    else:
        period = u.get_current_quarter()
    
    # in conteggio per il raggiungimento degli obiettivi è fatto sui contratti
    # inviati nel quarto di riferimento
    contratti_inviati = models.Contratto.objects.filter(data_inviato__gte=period[0], 
                                                        data_inviato__lte=period[1], 
                                                        inviato=True)\
                                                .order_by("data_inviato")\
                                                .select_related("piano_tariffario")
    
    # ricaviamo contratti solo degli agenti/telefonisti selezionati 
    if request.method == "GET" and request.GET.has_key("fagente"):
        agenti_ids = u.get_agenti_ids(request.GET)
        if agenti_ids:
            contratti_inviati = contratti_inviati.filter(agente__in=agenti_ids) 
    if request.method == "GET" and request.GET.has_key("ftelefonista"):
        tel_ids = u.get_telefonisti_ids(request.GET)
        if tel_ids:
            contratti_inviati = contratti_inviati.filter(telefonista__in=tel_ids)    
    
    obiettivi = models.Obiettivo.objects.filter(data_inizio__lte=period[0])
    
    d, totals = get_points(obiettivi, contratti_inviati)

#    totals = {}
#    for obiettivo in obiettivi:
#        totals[obiettivo.denominazione] = {"inviati": 0, 
#                                           "caricati": 0,
#                                           "punteggio": 0,}
#    d = {}
#    if contratti_inviati.exists():        
#        dates = contratti_inviati.values("data_inviato").distinct()
#
#        for date in dates:
#            data_inviato = date["data_inviato"].strftime("%d/%m/%Y")
#            d[data_inviato] = {}
#            
#            daily_points = get_daily_points(obiettivi, 
#                                            contratti_inviati, 
#                                            date["data_inviato"])
#            for denominazione in daily_points.keys():
#                d[data_inviato][denominazione] = {"data": data_inviato,
#                                                  "punteggio": daily_points[denominazione]["punteggio"],
#                                                  "inviati": daily_points[denominazione]["contratti"],}
#                totals[denominazione]["punteggio"] += daily_points[denominazione]["punteggio"]
#                totals[denominazione]["inviati"] += daily_points[denominazione]["contratti"]
#            for obiettivo in obiettivi:
#                punteggio_day = 0
#                
#                contratti_day = contratti_inviati.filter(data_inviato=date["data_inviato"])
#                n_inviati = 0
#                for contratto in contratti_day:
#                    # determiniamo il piano tariffario
#                    pts = models.PianoTariffario.objects.filter(contratto=contratto).iterator()
#                    
#                    punteggio_contratto = 0
#                    for pt in pts:
#                        q = pt.num
#                        tariffa = pt.tariffa      
#                        
#                        if check_tariffa(obiettivo, tariffa):
#                            punteggio_contratto = +q
#                    
#                    n_inviati += 1
#                    punteggio_day += punteggio_contratto
#                
#                d[data_inviato][obiettivo.denominazione] = {"data": data_inviato,
#                                                            "punteggio": punteggio_day,
#                                                            "inviati": n_inviati,}    
#                totals[obiettivo.denominazione]["punteggio"] += punteggio_day
#                totals[obiettivo.denominazione]["inviati"] += n_inviati
    
    rows = []        
    date_cur = period[0]
    today = datetime.today().date()
    y_cur = 0
    m_cur = 0
    
    while date_cur <= period[1]:
        if date_cur.year != y_cur:
            year = date_cur.year
            y_cur = date_cur.year
        else:
            year = None
        
        if date_cur.month != m_cur:
            m_cur = date_cur.month
            if date_cur == today:
                month = (date_cur.strftime("%B"), today)
            else:
                month = (date_cur.strftime("%B"), None)
        else:
            if date_cur == today:
                month = (None, today)
            else:    
                month = (None, None)
        
        row = {"anno": year, "mese": month}
        k = date_cur.strftime("%d/%m/%Y")
        if k in d:
            for obiettivo in obiettivi:
                row[obiettivo.denominazione] = d[k][obiettivo.denominazione]
        rows.append(row)
        date_cur += timedelta(1)
    
#    for obiettivo in obiettivi:
#        diff = obiettivo.punteggio - totals[obiettivo.denominazione]["punteggio"]
#        diff = totals[obiettivo.denominazione]["goal"]
#        if diff < 0:
#            totals[obiettivo.denominazione]["msg"] = "Obiettivo raggiunto (+{})".format(diff)
#        elif diff == 0:
#            totals[obiettivo.denominazione]["msg"] = "Obiettivo raggiunto"
#        else:
#            totals[obiettivo.denominazione]["msg"] = "Per raggiungere l'obiettivo mancano {} punti".format(diff)    
            
    if request.is_ajax():
        data = {"rows": rows, "obiettivi": obiettivi, "period": period, "totali": totals}
        return render_to_response(template,
                                  data,
                                  context_instance=RequestContext(request))        
    
    filterform = forms.ObiettivoFilterForm()
    data = {"rows": rows, "obiettivi": obiettivi, "period": period, 
            "totali": totals, "filterform": filterform,}
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))