Beispiel #1
0
    def __init__(self, initial=None, allow_past=False, **kwargs):
        if initial is None:
            initial = (None, None)

        if len(initial) != 2:
            raise ValueError(
                _("Initial data tuple was expected to have " +
                  " exactly two dates."))

        fields = (
            DateTimeField(
                initial=initial[0],
                input_formats=[
                    DATETIME_INPUT_FORMAT,
                ],
                **kwargs,
            ),
            DateTimeField(
                initial=initial[1],
                input_formats=[
                    DATETIME_INPUT_FORMAT,
                ],
                **kwargs,
            ),
        )

        super(DateTimeRangeField, self).__init__(fields,
                                                 initial=initial,
                                                 **kwargs)

        # Allow a time_range to be in the past
        self.allow_past = allow_past
    def test_use_24_hour_time_format_en(self):
        field = DateTimeField()
        supported_custom_examples = [
            '10/25/2006 2:30:59',
            '10/25/2006 2:30',
            '10/25/2006 14:30:59',
            '10/25/2006 14:30',
        ]

        for example in supported_custom_examples:
            try:
                result = field.to_python(example)
                self.assertIsInstance(result, datetime.datetime)
            except ValidationError:
                self.fail('Format of "{}" not recognized!'.format(example))

        with self.assertRaises(ValidationError):
            field.to_python('invalid date string!')

        dt = datetime.datetime(year=2011, month=11, day=4, hour=23, minute=5,
                               second=59)
        self.assertEqual(
            date_format(dt, 'DATETIME_FORMAT'), 'Nov. 4, 2011, 23:05:59')

        dt = datetime.datetime(year=2011, month=11, day=4, hour=2, minute=5,
                               second=59)
        self.assertEqual(
            date_format(dt, 'SHORT_DATETIME_FORMAT'), '11/04/2011 2:05:59')

        t = datetime.time(hour=16, minute=2, second=25)
        self.assertEqual(time_format(t), '16:02:25')
Beispiel #3
0
    def __init__(self, *args, **kwargs):
        super(MetaInlineForm, self).__init__(*args, **kwargs)
        self.show_edit_url = False  # shows edit button if set to True
        core_signals.request_finished.connect(
            receiver=MetaInlineForm.reset_export_enumerator)
        existing_object = False
        new_object = False
        id_initial = None
        from_initial = to_initial = ''
        export_initial = None
        position_initial = None
        #export_qs = models.Export.objects.all()
        if 'instance' in kwargs and 'data' not in kwargs:
            existing_object = True
            instance = kwargs['instance']
            if instance:
                initial = self.get_initial_data(instance)
                id_initial = initial['pk']
                from_initial = initial['visible_from']
                to_initial = initial['visible_to']
                export_initial = initial['export_pk']
                position_initial = initial['position']
        elif 'data' not in kwargs:
            new_object = True

        self.assign_init_field(
            'position_id',
            HiddenIntegerField(initial=id_initial, label=u'', required=False))
        self.assign_init_field(
            'position_from',
            DateTimeField(initial=from_initial,
                          label=_('Visible From'),
                          widget=widgets.DateTimeWidget))
        self.assign_init_field(
            'position_to',
            DateTimeField(initial=to_initial,
                          label=_('Visible To'),
                          widget=widgets.DateTimeWidget,
                          required=False))
        self.assign_init_field(
            'position',
            IntegerField(initial=position_initial,
                         label=_('Position'),
                         required=False))
        export_field = fields.AdminSuggestField(
            models.ExportPosition._meta.get_field('export'),
            required=True,
            label=_('Export'),
            model=models.Export,
            lookup=(
                'title',
                'slug',
            ),
            initial=export_initial)
        #modelforms.ModelChoiceField(export_qs, initial=export_initial, label=_('Export'), show_hidden_initial=True)
        self.assign_init_field('export', export_field)
Beispiel #4
0
 def listings_clean(self, data):
     # get listing category, publish_from and publish_to
     pub_from = data.getlist(self.get_part_id('publish_from'))
     listings = self.cleaned_data['listings']
     if len(pub_from) and (len(pub_from) != len(listings)):
         raise ValidationError(_('Amount of publish_from input fields should be the same as category fields. With kind regards Your PlacementInline and his ListingCustomWidget.'))
     for lst, pub in zip(listings, pub_from):
         if not pub:
             #raise ValidationError(_('This field is required'))
             continue
         dt_field = DateTimeField()
         publish_from = dt_field.clean(pub)
def fc_events(request):
    """
    Returns events in JSON for FullCalendar

    It returns validated reservations between start and end GET parameters
    """
    # Get only events corresponding to the time slot
    start_time = request.GET.get('start')
    end_time = request.GET.get('end')
    if start_time and end_time:
        start = DateTimeField().clean(start_time.replace('T', ' '))
        end = DateTimeField().clean(end_time.replace('T', ' '))
        queryset = Reservation.objects.filter(
            start_time__lt=end,
            end_time__gt=start,
        )
    else:
        queryset = Reservation.objects

    data = []

    # Add user reservation
    for reservation in queryset.filter(in_charge=request.user):
        event = {
            'resourceId': reservation.room.id,
            'title': reservation.purpose_title,
            'start': timezone.localtime(reservation.start_time),
            'end': timezone.localtime(reservation.end_time),
            'url': reverse('edit', args=(reservation.id, )),
        }
        if reservation.validation:
            event['comment'] = _('Validated')
            event['color'] = 'green'
        elif reservation.validation is None:
            event['comment'] = _('Being validated')
            event['color'] = 'black'
        else:
            event['comment'] = _('Denied')
            event['color'] = 'red'
        data.append(event)

    # Add all other reservation
    for reservation in \
            queryset.filter(validation=True).exclude(in_charge=request.user):
        event = {
            'resourceId': reservation.room.id,
            'title': reservation.purpose_title,
            'start': timezone.localtime(reservation.start_time),
            'end': timezone.localtime(reservation.end_time),
        }
        data.append(event)

    return JsonResponse(data, safe=False)
Beispiel #6
0
 def listings_clean(self, placement_publish_from, data):
     # get listing category, publish_from and publish_to
     pub_from = data.getlist(self.get_part_id('publish_from'))
     listings = self.cleaned_data['listings']
     if pub_from and len(pub_from) != len(listings):
         raise ValidationError(_('Duplicate listings'))
     for lst, pub in zip(listings, pub_from):
         if not pub:
             #raise ValidationError(_('This field is required'))
             continue
         dt_field = DateTimeField()
         publish_from = dt_field.clean(pub)
         if publish_from < placement_publish_from:
             raise ValidationError(_('No listing can start sooner than main listing'))
Beispiel #7
0
 def listings_clean(self, placement_publish_from, data):
     # get listing category, publish_from and publish_to
     pub_from = data.getlist(self.get_part_id("publish_from"))
     listings = self.cleaned_data["listings"]
     if pub_from and len(pub_from) != len(listings):
         raise ValidationError(_("Duplicate listings"))
     for lst, pub in zip(listings, pub_from):
         if not pub:
             # raise ValidationError(_('This field is required'))
             continue
         dt_field = DateTimeField()
         publish_from = dt_field.clean(pub)
         if publish_from < placement_publish_from:
             raise ValidationError(_("No listing can start sooner than main listing"))
Beispiel #8
0
    def test_datetime_input_formats(self):
        field = DateTimeField()
        supported_custom_examples = [
            '01/20/2020 9:30 AM',
            '01/20/2020 9:30:03 AM',
            '10/01/2020 11:30 PM',
            '10/01/2020 11:30:03 AM',
        ]

        for example in supported_custom_examples:
            result = field.to_python(example)
            self.assertIsInstance(result, datetime.datetime)

        with self.assertRaises(ValidationError):
            field.to_python('invalid date string!')
    def test_format_translation(self):
        translations = {
            '%Y-%m-%d': 'yyyy-mm-dd',
            '%m/%d/%Y': 'mm/dd/yyyy',
            '%m/%d/%y': 'mm/dd/yy',
            '%b %d %Y': 'M dd yyyy',
            '%b %d, %Y': 'M dd, yyyy',
            '%d %b %Y': 'dd M yyyy',
            '%d %b, %Y': 'dd M, yyyy',
            '%B %d %Y': 'MM dd yyyy',
            '%B %d, %Y': 'MM dd, yyyy',
            '%d %B %Y': 'dd MM yyyy',
            '%d %B, %Y': 'dd MM, yyyy',
            '%Y-%m-%d %H:%M:%S': 'yyyy-mm-dd hh:ii:ss',
            '%Y-%m-%d %H:%M': 'yyyy-mm-dd hh:ii',
            '%m/%d/%Y %H:%M:%S': 'mm/dd/yyyy hh:ii:ss',
            '%m/%d/%Y %H:%M': 'mm/dd/yyyy hh:ii',
            '%m/%d/%y %H:%M:%S': 'mm/dd/yy hh:ii:ss',
            '%m/%d/%y %H:%M': 'mm/dd/yy hh:ii',
        }

        for input_format, output_format in translations.items():
            field = DateTimeField(input_formats=[input_format])
            result = viewform.datepicker_format(field)
            self.assertEqual(output_format, result)
class SharedForm(forms.Form):
    # name = forms.CharField(label='Your Email', max_length=200, required=True)
    dest = forms.CharField(label='Destination', max_length=100, required=True)
    earliest_arrival = DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],
                                     widget=DateTimeInput(
                                         format='%Y-%m-%dT%H:%M',
                                         attrs={'type': 'datetime-local'}))
    latest_arrival = DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],
                                   widget=DateTimeInput(
                                       format='%Y-%m-%dT%H:%M',
                                       attrs={'type': 'datetime-local'}))
    pnum = forms.IntegerField(
        label='Number of Passengers',
        required=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(6)])
Beispiel #11
0
 def to_python(self, value):
     try:
         date = dateutil.parser.parse(value)
     except ValueError:
         #Date utils couldn't figure it out.  Let the default parser have a
         #swing at it and throw errors as necessary.
         date = value
     return DateTimeField.to_python(self, date)
 def factory_method(cls, **kwargs) -> Message:
     translation = {
         "identifier": "identifier",
         "object_user": "******",
         "object_channel": "channel",
         "date": "date",
         "content": "content",
         "author_id": "author_id",
         "references_id": "references_id",
     }
     translated_args = cls.translate_kwargs(cls,
                                            translation=translation,
                                            args=kwargs)
     date = DateTimeField().clean(translated_args["date"])
     tz = pytz.timezone("Europe/Paris")
     date.replace(tzinfo=tz)
     translated_args["date"] = date
     return Message(**translated_args)
Beispiel #13
0
    def test_datetime_input_formats(self):
        update_en_us_date_formats()
        field = DateTimeField()
        supported_custom_examples = [
            "01/20/2020 9:30 AM",
            "01/20/2020 9:30:03 AM",
            "10/01/2020 11:30 PM",
            "10/01/2020 11:30:03 AM",
        ]

        for example in supported_custom_examples:
            try:
                result = field.to_python(example)
                self.assertIsInstance(result, datetime.datetime)
            except ValidationError:
                self.fail('Format of "{}" not recognized!'.format(example))

        with self.assertRaises(ValidationError):
            field.to_python("invalid date string!")
Beispiel #14
0
class Post(db.Document):
    id = Integer(primary_key=True)
    title = StringField(required=True)
    date_posted = DateTime(nullable=False, default=datetime.utcnow())
    content = StringField(Text, nullable=False)
    last_updated = DateTimeField(default=datetime.datetime.now())
    user_id = Integer(ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}')"
Beispiel #15
0
    def test_use_24_hour_time_format(self):
        update_en_gb_date_formats()
        field = DateTimeField()
        supported_custom_examples = [
            "25/10/2006 2:30:59",
            "25/10/2006 2:30",
            "25/10/2006 14:30:59",
            "25/10/2006 14:30",
        ]

        for example in supported_custom_examples:
            try:
                result = field.to_python(example)
                self.assertIsInstance(result, datetime.datetime)
            except ValidationError:
                self.fail('Format of "{}" not recognized!'.format(example))

        with self.assertRaises(ValidationError):
            field.to_python("invalid date string!")

        dt = datetime.datetime(year=2011,
                               month=11,
                               day=4,
                               hour=23,
                               minute=5,
                               second=59)
        self.assertEqual(date_format(dt, "DATETIME_FORMAT"),
                         "4 November 2011 23:05:59")

        dt = datetime.datetime(year=2011,
                               month=11,
                               day=4,
                               hour=2,
                               minute=5,
                               second=59)
        self.assertEqual(date_format(dt, "SHORT_DATETIME_FORMAT"),
                         "04/11/2011 02:05")

        t = datetime.time(hour=16, minute=2, second=25)
        self.assertEqual(time_format(t), "16:02")
Beispiel #16
0
    def get_incidents_for_period(self, period):

        today = timezone.now()
        datem = datetime(today.year, today.month, 1)

        from_date = datem - relativedelta(months=+(period - 1) * 3)
        to_date = datem - relativedelta(months=+(period * 3))

        period = "%(from)s - %(to)s" % {
            "from": from_date.strftime("%B %Y"),
            "to": (to_date + relativedelta(months=+1)).strftime("%B %Y")
        }

        from_date = datetime(from_date.year, from_date.month, 1)
        to_date = datetime(to_date.year, to_date.month, 1)

        incidents = []
        while from_date > to_date:
            current_incidents = []

            incidents_list = self.__incident_entity.get_incident_on_month(
                DateTimeField().clean(from_date))

            for incident in incidents_list:
                current_incidents.append({
                    "uri":
                    incident.uri,
                    "subject":
                    incident.name,
                    "class":
                    "text-danger",
                    "status":
                    incident.status,
                    "final_update":
                    _("This incident has been resolved.") if incident.status
                    == "closed" else _("This incident is still open."),
                    "period":
                    self.__get_incident_period(incident)
                })

            current_date = from_date.strftime("%B %Y")
            incidents.append({
                "date": current_date,
                "incidents": current_incidents
            })
            from_date -= relativedelta(months=+1)

        return {"period": period, "incidents": incidents}
class RequestForm(forms.Form):
    destination = forms.CharField(label='Destination',
                                  max_length=100,
                                  required=True)

    arrival_time = DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],
                                 widget=DateTimeInput(
                                     format='%Y-%m-%dT%H:%M',
                                     attrs={'type': 'datetime-local'}))

    party_size = forms.IntegerField(
        label='Number of Passengers',
        required=True,
        validators=[MinValueValidator(1),
                    MaxValueValidator(6)])
    vehicle = forms.ChoiceField(label='Vehicle Type',
                                choices=(("Sedan", "Sedan"), ("SUV", "SUV")))

    sharable = forms.BooleanField(required=False)
    special_request = forms.CharField(label='Special Request',
                                      max_length=100,
                                      required=False)
Beispiel #18
0
	def setUpTestData(cls):
		''' Set up localized deadline-date for tasks, create dummy tasks '''
		cls.deadline_date = DateTimeField().clean('2030-06-04 13:00')
		TaskUtilsTestCase.deadline_date = TaskUtilsTestCase.deadline_date.replace(tzinfo=None)
		tz = pytz.timezone('Europe/Berlin')
		tz.localize(TaskUtilsTestCase.deadline_date)
		cls.date = timezone.now()
		cls.person = Person.objects.create_user(username = '******', password = '******', position = 'BOS')
		cls.task1 = Task.objects.create(priority = 'LOW',assigned_employee = cls.person,  task_name = 'dummy task', 
			task_description = 'dummy_task', created_date = TaskUtilsTestCase.date, 
			deadline_date = TaskUtilsTestCase.deadline_date)
		cls.task2 =  Task.objects.create(priority = 'LOW',assigned_employee = cls.person,  task_name = 'dummy task', 
			task_description = 'dummy_task', created_date = TaskUtilsTestCase.date, 
			deadline_date = TaskUtilsTestCase.date)
		cls.task3 = Task.objects.create(priority = 'HIG',assigned_employee = cls.person,  task_name = 'dummy task', 
			task_description = 'dummy_task', created_date = TaskUtilsTestCase.date, 
			deadline_date = TaskUtilsTestCase.deadline_date)
		cls.task4 = Task.objects.create(priority = 'CRI',assigned_employee = cls.person,  task_name = 'dummy task', 
			task_description = 'dummy_task', created_date = TaskUtilsTestCase.date, 
			deadline_date = TaskUtilsTestCase.deadline_date)
		cls.task5 = Task.objects.create(priority = 'MED',assigned_employee = cls.person,  task_name = 'dummy task', 
			task_description = 'dummy_task', created_date = TaskUtilsTestCase.date, 
			deadline_date = TaskUtilsTestCase.deadline_date)
Beispiel #19
0
class ServiceCallContext(SoColissimoSchema):
    soap_type_name = "ServiceCallContextV2"

    dateDeposite = DateTimeField(required=True)
    commercialName = CharField(required=True)

    VATCode = ChoiceField(required=False,
                          choices=[(vat, vat) for vat in range(3)])
    VATPercentage = IntegerField(required=False, min_value=0, max_value=9999)
    VATAmount = IntegerField(required=False, min_value=0)
    transportationAmount = IntegerField(required=False, min_value=0)
    totalAmount = IntegerField(required=False, min_value=0)
    commandNumber = CharField(required=False)

    def _set_constants(self, service):
        service.dateValidation = datetime.datetime.today(
        ) + datetime.timedelta(7)
        service.returnType = 'CreatePDFFile'
        service.serviceType = 'SO'
        service.crbt = False

        service.portPaye = False
        service.languageConsignor = "FR"
        service.languageConsignee = "FR"
Beispiel #20
0
 def get_publish_date(self, pub_from):
     " Tries to save publish_from field specified either by POST parameter or by Placement (self.instance). "
     if pub_from:
         dt_field = DateTimeField()
         return dt_field.clean(pub_from)
     return self.instance.publish_from
Beispiel #21
0
class MetaInlineForm(modelforms.ModelForm):
    _export_stack = dict()
    position_id = HiddenIntegerField(required=False)
    position_from = DateTimeField(label=_('Visible From'),
                                  widget=widgets.DateTimeWidget)
    position_to = DateTimeField(label=_('Visible To'),
                                widget=widgets.DateTimeWidget,
                                required=False)
    position = IntegerField(required=False)
    export = fields.AdminSuggestField(
        models.ExportPosition._meta.get_field('export'),
        required=True,
        label=_('Export'),
        model=models.Export,
        lookup=(
            'title',
            'slug',
        ),
    )
    # override base_fields and include all the other declared fields
    declared_fields = SortedDict(
        (('title', HiddenIntegerField(label=u'', required=False)),
         ('position_id', HiddenIntegerField(label=u'', required=False)),
         ('position_from',
          DateTimeField(label=_('Visible From'),
                        widget=widgets.DateTimeWidget)),
         ('position_to',
          DateTimeField(label=_('Visible To'),
                        widget=widgets.DateTimeWidget,
                        required=False)), ('position',
                                           IntegerField(required=False)),
         ('export',
          fields.AdminSuggestField(
              models.ExportPosition._meta.get_field('export'),
              required=True,
              label=_('Export'),
              model=models.Export,
              lookup=(
                  'title',
                  'slug',
              ),
          ))))

    def __init__(self, *args, **kwargs):
        super(MetaInlineForm, self).__init__(*args, **kwargs)
        self.show_edit_url = False  # shows edit button if set to True
        core_signals.request_finished.connect(
            receiver=MetaInlineForm.reset_export_enumerator)
        existing_object = False
        new_object = False
        id_initial = None
        from_initial = to_initial = ''
        export_initial = None
        position_initial = None
        #export_qs = models.Export.objects.all()
        if 'instance' in kwargs and 'data' not in kwargs:
            existing_object = True
            instance = kwargs['instance']
            if instance:
                initial = self.get_initial_data(instance)
                id_initial = initial['pk']
                from_initial = initial['visible_from']
                to_initial = initial['visible_to']
                export_initial = initial['export_pk']
                position_initial = initial['position']
        elif 'data' not in kwargs:
            new_object = True

        self.assign_init_field(
            'position_id',
            HiddenIntegerField(initial=id_initial, label=u'', required=False))
        self.assign_init_field(
            'position_from',
            DateTimeField(initial=from_initial,
                          label=_('Visible From'),
                          widget=widgets.DateTimeWidget))
        self.assign_init_field(
            'position_to',
            DateTimeField(initial=to_initial,
                          label=_('Visible To'),
                          widget=widgets.DateTimeWidget,
                          required=False))
        self.assign_init_field(
            'position',
            IntegerField(initial=position_initial,
                         label=_('Position'),
                         required=False))
        export_field = fields.AdminSuggestField(
            models.ExportPosition._meta.get_field('export'),
            required=True,
            label=_('Export'),
            model=models.Export,
            lookup=(
                'title',
                'slug',
            ),
            initial=export_initial)
        #modelforms.ModelChoiceField(export_qs, initial=export_initial, label=_('Export'), show_hidden_initial=True)
        self.assign_init_field('export', export_field)

    def assign_init_field(self, field_name, value):
        self.fields[field_name] = self.base_fields[field_name] = value

    def get_initial_data(self, instance):
        " @return dict (visible_from, visible_to, export_initial, position) "
        positions = models.ExportPosition.objects.filter(object=instance)
        out = {
            'pk': '',
            'visible_from': '',
            'visible_to': None,
            'export_pk': None,
            'position': ''
        }
        if not positions:
            return out
        pcount = positions.count()
        if pcount > 1 and not MetaInlineForm._export_stack.get(
                instance, False):
            MetaInlineForm._export_stack[instance] = list()
            map(lambda p: MetaInlineForm._export_stack[instance].insert(0, p),
                positions)
        if pcount == 1:
            pos = positions[0]
        elif pcount > 1:
            pos = MetaInlineForm._export_stack[instance].pop()
        out.update({
            'pk': pos.pk,
            'visible_from': pos.visible_from,
            'visible_to': pos.visible_to,
            'export_pk': pos.export.pk,
            'position': pos.position
        })
        return out

    @staticmethod
    def reset_export_enumerator(*args, **kwargs):
        " Clears _export_stack at the end of HTTP request. "
        core_signals.request_finished.disconnect(
            receiver=MetaInlineForm.reset_export_enumerator)
        MetaInlineForm._export_stack.clear()

    def get_date_field_key(self, field):
        return '%s-%s' % (self.prefix, field)

    def clean(self):
        """
        if not self.is_valid() or not self.cleaned_data or not self.instance:
            return self.cleaned_data
        """
        self.cleaned_data['position_id'] = self.data[self.get_date_field_key(
            'position_id')]
        self.cleaned_data['position_from'] = self.data[self.get_date_field_key(
            'position_from')]
        self.cleaned_data['position'] = self.data[self.get_date_field_key(
            'position')]
        data_position_to = self.data[self.get_date_field_key('position_to')]
        if data_position_to:
            self.cleaned_data['position_to'] = data_position_to
        self.cleaned_data['export'] = self.data[self.get_date_field_key(
            'export')]
        return self.cleaned_data

    def save(self, commit=True):
        out = super(MetaInlineForm, self).save(commit=commit)

        def save_them():
            export = models.Export.objects.get(
                pk=int(self.cleaned_data['export']))
            positions = models.ExportPosition.objects.filter(
                object=self.instance, export=export)
            if not self.cleaned_data['position_id']:
                position = models.ExportPosition(object=self.instance, )
            else:
                pos_id = int(self.cleaned_data['position_id'])
                position = models.ExportPosition.objects.get(pk=pos_id)
            position.export = export
            position.visible_from = self.cleaned_data['position_from']
            position.visible_to = self.cleaned_data['position_to']
            if self.cleaned_data['position'].isdigit():
                position.position = int(self.cleaned_data['position'])
            position.save()

        if commit:
            save_them()
        else:
            save_m2m = getattr(self, 'save_m2m', None)

            def save_all():
                if save_m2m:
                    save_m2m()
                save_them()

            self.save_m2m = save_all
        return out
Beispiel #22
0
    def post(self, request, incident_id, update_id):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "status": "",
            "notify_subscribers": "",
            "message": "",
            "datetime": "",
        })

        self.__form.add_inputs({
            'message': {
                'value': request_data["message"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 3000000],
                        'error': _('Error! Update message must be 1 to 3M characters long.')
                    }
                }
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_datetime': {
                        'error': _('Error! Datetime is invalid.')
                    }
                }
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["investigating", "identified", "monitoring", "update", "resolved"]],
                        'error': _('Error! Status is invalid.')
                    }
                }
            },
            'notify_subscribers': {
                'value': request_data["notify_subscribers"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Notify subscribers is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        result = self.__incident_update.update_one_by_id(update_id, {
            "notify_subscribers": self.__form.get_sinput("notify_subscribers"),
            "datetime": DateTimeField().clean(self.__form.get_sinput("datetime")),
            "message": self.__form.get_sinput("message"),
            "status": self.__form.get_sinput("status")
        })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Incident update updated successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while updating update.")
            }], {}, self.__correlation_id))
Beispiel #23
0
    def get_filter_params(self):
        """Preparing parameters for change list queryset, based on attached queries."""

        filter_params = {}
        exclude_params = {}
        bundled_params = {}

        field = DateTimeField()

        for query in self.queries.all():
            if query.model_field:
                key = query.field
                if query.criteria:  # avoiding load of empty criteria
                    dates_criterias = [
                        'today', 'this_week', 'this_month', 'this_year',
                        'between', 'days_ago'
                    ]
                    if query.criteria not in dates_criterias:
                        if type(query.field_value) is list:
                            if len(query.field_value) > 1:
                                key += '__in'
                            query.field_value = ','.join(query.field_value)
                            if query.field_type in ('datetime', 'date'):
                                field = DateTimeField()
                                query.value = field.to_python(
                                    query.field_value)
                        else:
                            key += '__%s' % query.criteria
                    elif type(query.field_value) is list and len(
                            query.field_value
                    ) > 1 and query.criteria not in dates_criterias:
                        if query.criteria != 'between':
                            key += '__in'
                    # preparing date-related criteria
                    if query.criteria in [
                            'today', 'this_week', 'this_month', 'this_year',
                            'days_ago'
                    ]:
                        date = datetime.datetime.now()
                        value = None
                        if query.criteria == 'today':
                            value = date.strftime('%Y-%m-%d')
                        if query.criteria == 'this_month':
                            # we need to filter by current year to make sure we have only from this month,
                            # not all records with month with given number
                            filter_params[key + '__year'] = date.strftime('%Y')

                            key += '__month'
                            value = date.strftime('%m')
                        if query.criteria == 'this_year':
                            key += '__year'
                            value = date.strftime('%Y')

                        if query.criteria == 'this_week':
                            date = datetime.date.today()
                            start_week = date - datetime.timedelta(
                                date.weekday())
                            end_week = start_week + datetime.timedelta(7)
                            key += '__range'
                            value = [start_week, end_week]
                        filter_params[key] = value
                        if query.criteria == 'days_ago':
                            date = datetime.date.today() - datetime.timedelta(
                                days=int(query.field_value))
                            del (filter_params[key])
                            filter_params[key + '__year'] = date.year
                            filter_params[key + '__month'] = date.month
                            filter_params[key + '__day'] = date.day
                    elif query.criteria == 'between':
                        start_value = query.field_value[0]
                        end_value = query.field_value[0]
                        if query.field_type in ('date', 'datetime'):
                            start_value = field.to_python(
                                query.field_value[0]
                            ) if start_value else start_value
                            end_value = field.to_python(
                                query.field_value[1]
                            ) if end_value else end_value
                        if query.field_value[0]:
                            filter_params['%s__gt' % key] = start_value
                        if query.field_value[1]:
                            filter_params['%s__lte' % key] = end_value
                    elif query.criteria == '_notcontains':
                        exclude_params[key + '__icontains'] = query.field_value
                    elif query.criteria == 'not':
                        exclude_params[key[:-5]] = query.field_value
                    elif query.criteria == 'startswith':
                        filter_params[key + '__startswith'] = query.field_value
                    elif query.criteria == 'endswith':
                        filter_params[key + '__endswith'] = query.field_value

                    elif query.field_value:  # avoiding load of empty filter value which causes database error
                        if query.model_field.get_internal_type(
                        ) == 'BooleanField':
                            filter_params[key] = {
                                'true': True,
                                'false': False
                            }[query.field_value]
                        else:
                            if query.criteria in ('lt', 'gt'):
                                if not key.endswith('__' + query.criteria):
                                    key = key + '__' + query.criteria
                                filter_params[key] = query.field_value
                            else:
                                filter_params[key] = query.field_value
                            if query.field_type in (
                                    'date', 'datetime'
                            ) and query.field_value and query.criteria not in (
                                    'lt', 'gt'):
                                date = field.to_python(query.field_value)
                                # needed to cover case when field is datetime and time is not specified
                                if not date.hour and not date.minute and not date.second:
                                    del (filter_params[key])
                                    filter_params[query.field +
                                                  '__year'] = date.year
                                    filter_params[query.field +
                                                  '__month'] = date.month
                                    filter_params[query.field +
                                                  '__day'] = date.day

        for query in self.bundled_queries.all():
            bundled_params[query.field] = query.value
        return filter_params, exclude_params, bundled_params
Beispiel #24
0
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "status": "",
            "datetime": "",
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 200],
                        'error':
                        _('Error! Incident name must be 1 to 200 characters long.'
                          )
                    }
                }
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["open", "closed"]],
                        'error': _('Error! Incident is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        result = self.__incident.insert_one({
            "name":
            self.__form.get_sinput("name"),
            "status":
            self.__form.get_sinput("status"),
            "datetime":
            DateTimeField().clean(self.__form.get_sinput("datetime")),
            "uri":
            self.__incident.generate_uri(6)
        })

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Incident created successfully.")
                    }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating incident.")
                }], {}, self.__correlation_id))
Beispiel #25
0
 def get_publish_date(self, pub_from):
     " Tries to save publish_from field specified either by POST parameter or by Placement (self.instance). "
     if pub_from:
         dt_field = DateTimeField()
         return dt_field.clean(pub_from)
     return self.instance.publish_from
Beispiel #26
0
    def get_filter_params(self):
        """Preparing parameters for change list queryset, based on attached queries."""
        
        filter_params = {}
        exclude_params = {}
        bundled_params = {}

        field = DateTimeField()

        for query in self.queries.all():
            if query.model_field:
                key = query.field
                if query.criteria:  # avoiding load of empty criteria
                    dates_criterias = ['today', 'this_week', 'this_month', 'this_year', 'between', 'days_ago']
                    if query.criteria not in dates_criterias:
                        if type(query.field_value) is list:
                            if len(query.field_value) > 1:
                                key += '__in'
                            query.field_value = ','.join(query.field_value)
                            if query.field_type in ('datetime', 'date'):
                                field = DateTimeField()
                                query.value = field.to_python(query.field_value)
                        else:
                            key += '__%s' % query.criteria
                    elif type(query.field_value) is list and len(query.field_value) > 1 and query.criteria not in dates_criterias:
                        if query.criteria != 'between':
                            key += '__in'
                    # preparing date-related criteria
                    if query.criteria in ['today', 'this_week', 'this_month', 'this_year', 'days_ago']:
                        date = datetime.datetime.now()
                        value = None
                        if query.criteria == 'today':
                            value = date.strftime('%Y-%m-%d')
                        if query.criteria == 'this_month':
                            # we need to filter by current year to make sure we have only from this month,
                            # not all records with month with given number
                            filter_params[key + '__year'] = date.strftime('%Y')

                            key += '__month'
                            value = date.strftime('%m')
                        if query.criteria == 'this_year':
                            key += '__year'
                            value = date.strftime('%Y')

                        if query.criteria == 'this_week':
                            date = datetime.date.today()
                            start_week = date - datetime.timedelta(date.weekday())
                            end_week = start_week + datetime.timedelta(7)
                            key += '__range'
                            value = [start_week, end_week]
                        filter_params[key] = value
                        if query.criteria == 'days_ago':
                            date = datetime.date.today() - datetime.timedelta(days=int(query.field_value))
                            del(filter_params[key])
                            filter_params[key + '__year'] = date.year
                            filter_params[key + '__month'] = date.month
                            filter_params[key + '__day'] = date.day
                    elif query.criteria == 'between':
                        start_value = query.field_value[0]
                        end_value = query.field_value[0]
                        if query.field_type in ('date', 'datetime'):
                            start_value = field.to_python(query.field_value[0]) if start_value else start_value
                            end_value = field.to_python(query.field_value[1]) if end_value else end_value
                        if query.field_value[0]:
                            filter_params['%s__gt' % key] = start_value
                        if query.field_value[1]:
                            filter_params['%s__lte' % key] = end_value
                    elif query.criteria == '_notcontains':
                        exclude_params[key + '__icontains'] = query.field_value
                    elif query.criteria == 'not':
                        exclude_params[key[:-5]] = query.field_value
                    elif query.criteria == 'startswith':
                        filter_params[key + '__startswith'] = query.field_value
                    elif query.criteria == 'endswith':
                        filter_params[key + '__endswith'] = query.field_value

                    elif query.field_value:     # avoiding load of empty filter value which causes database error
                        if query.model_field.get_internal_type() == 'BooleanField':
                            filter_params[key] = {'true': True, 'false': False}[query.field_value]
                        else:
                            if query.criteria in ('lt', 'gt'):
                                if not key.endswith('__' + query.criteria):
                                    key = key + '__' + query.criteria
                                filter_params[key] = query.field_value
                            else:
                                filter_params[key] = query.field_value
                            if query.field_type in ('date', 'datetime') and query.field_value and query.criteria not in ('lt', 'gt'):
                                date = field.to_python(query.field_value)
                                # needed to cover case when field is datetime and time is not specified
                                if not date.hour and not date.minute and not date.second:
                                    del(filter_params[key])
                                    filter_params[query.field + '__year'] = date.year
                                    filter_params[query.field + '__month'] = date.month
                                    filter_params[query.field + '__day'] = date.day

        for query in self.bundled_queries.all():
            bundled_params[query.field] = query.value
        return filter_params, exclude_params, bundled_params
def datetimetype(s):
    f = DateTimeField()
    try:
        return f.to_python(s)
    except ValidationError as e:
        raise argparse.ArgumentTypeError("Unrecognized datetime format") from e
Beispiel #28
0
    def post(self, request, incident_id):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "status": "",
            "notify_subscribers": "",
            "message": "",
            "datetime": "",
        })

        self.__form.add_inputs({
            'message': {
                'value': request_data["message"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["investigating", "identified", "monitoring", "update", "resolved"]],
                        'error': _('Error! Status is invalid.')
                    }
                }
            },
            'notify_subscribers': {
                'value': request_data["notify_subscribers"],
                'validate': {
                    'any_of': {
                        'param': [["on", "off"]],
                        'error': _('Error! Notify subscribers is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        result = self.__incident_update.insert_one({
            "notify_subscribers": self.__form.get_sinput("notify_subscribers"),
            "datetime": DateTimeField().clean(self.__form.get_sinput("datetime")),
            "total_suscribers": self.__subscriber.count_by_status(SubscriberModule.VERIFIED),
            "message": self.__form.get_sinput("message"),
            "status": self.__form.get_sinput("status"),
            "incident_id": incident_id
        })

        if self.__form.get_sinput("status") == "resolved":
            self.__incident.update_one_by_id(incident_id, {
                "status": "closed"
            })
        else:
            self.__incident.update_one_by_id(incident_id, {
                "status": "open"
            })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Incident update created successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating update.")
            }], {}, self.__correlation_id))
Beispiel #29
0
    def save(self, *args, **kwargs):
        params = self.data
        if params.get('e'):
            return
        filter_ordering = params.getlist('ordering', None)
        if '' in filter_ordering:
            filter_ordering.remove('')
        self.custom_filter.filter_ordering = filter_ordering
        for query in self.custom_filter.bundled_queries.all():
            query_instance = query.query_instance(None, {}, self.custom_filter.model, None)
            if params.get('%s_enabled' % query_instance.parameter_name, None):
                criteria = params.get('%s_criteria' % query_instance.parameter_name, None)
                query.field = query_instance.parameter_name
                query.value = criteria
                query.save()
            else:
                query.delete()
        for query in list(self.custom_filter.queries.all()) + self.new_fields:
            if not isinstance(query, CustomQuery):
                query = CustomQuery(custom_filter=self.custom_filter, field=query)
            if params.get('%s_enabled' % query.field, None):
                criteria = params.get('%s_criteria' % query.field, 'exact')
                query.criteria = criteria
                value = params.getlist('%s_value' % query.field, None)

                # some sort of hack to detect if we have multiple values
                if not query.is_multiple and not len(value):
                    value = params.get('%s_value' % query.field, None)

                days_ago = params.get('%s_dago' % query.field, None)

                field = DateTimeField()

                if criteria == 'between':
                    if query.field_type == 'date':
                        start = params.get('%s_start' % query.field, '')
                        end = params.get('%s_end' % query.field, '')
                    else:
                        start = field.to_python('%s %s' % (params.get('%s_start_0' % query.field, ''), params.get('%s_start_1' % query.field, '')))
                        end = field.to_python('%s %s' % (params.get('%s_end_0' % query.field, ''), params.get('%s_end_1' % query.field, '')))
                    query.is_multiple = True
                    query.field_value = [str(start), str(end)]
                elif criteria in ('lt', 'gt') and query.field_type in ('date', 'datetime'):
                    start = field.to_python('%s %s' % (params.get('%s_value_0' % query.field, ''), params.get('%s_value_1' % query.field, '')))
                    query.field_value = str(start)
                elif criteria == 'days_ago':
                    query.field_value = days_ago
                elif criteria == 'this_week':
                    value = None
                elif days_ago and not value and criteria not in ['this_year']:
                    query.field_value = field.to_python('%s %s' % (params.get('%s_value_0' % query.field, ''), params.get('%s_value_1' % query.field, '')))
                elif query.field_type == 'datetime' and criteria == 'exact':
                    query.field_value = field.to_python('%s %s' % (params.get('%s_value_0' % query.field, ''), params.get('%s_value_1' % query.field, '')))
                else:
                    query.is_multiple = True if (isinstance(value, list) and len(value) > 1) else False
                    query.field_value = value

                # some sort of hack to detect if we have multiple values
                if not query.is_multiple and isinstance(value, list) and len(value) == 1:
                    query.value = value[0]

                query.save()
            else:
                query.delete()
        self.custom_filter.save()
Beispiel #30
0
class AccountForm(forms.Form):
    create_after = DateTimeField(label='在此之后创建:',required=False, widget=MyDateInput())
    name = CharField(label='开户人姓名',max_length=Customer._meta.get_field('name').max_length,required=False)
    bank = ModelChoiceField(SubBank.objects.all(),label='所属支行',required=False)
Beispiel #31
0
    def __init__(self, *args, **kwargs):
        """Preparing form - it consists of dynamic fields, except ordering."""
        
        self.custom_filter = kwargs.pop('custom_filter', None)
        self.custom_filters = kwargs.pop('custom_filters', None)
        self.request = kwargs.pop('request', None)
        self.model_admin = kwargs.pop('model_admin', None)
        self.new_query = kwargs.pop('new_query', None)
        super(CustomFilterForm, self).__init__(*args, **kwargs)
        if type(self.data) == dict:
            self.data = QueryDict(self.data)
        self.skip_validation = True
        self.params = args[0] if args else QueryDict('')
        all_fields = [f.replace('_enabled', '') for f in self.data if f.endswith('_enabled')]
        self.new_fields = [f for f in all_fields if f not in self.custom_filter.all_queries_names]
        if self.new_query:
            self.data['%s_enabled' % self.new_query] = 'on'
            self.new_fields.append(self.new_query)
        
        if isinstance(self.custom_filter.filter_ordering, list):
            ordering_choices = self.custom_filter.ordering_choices
            ordering_field = forms.MultipleChoiceField(required=False)
        else:
            widget = forms.Select(attrs={'class': 'single_ordering'})
            ordering_choices = [('', '')] + self.custom_filter.ordering_choices
            ordering_field = forms.ChoiceField(widget=widget, required=False)
        self.fields['ordering'] = ordering_field
        self.fields['ordering'].choices = ordering_choices
        self.fields['ordering'].initial = self.custom_filter.filter_ordering
        
        if self.custom_filter.choices:
            self.fields[ADMINFILTERS_ADD_PARAM] = forms.ChoiceField(label=_(u'Add field to filter:'), 
                                                                    widget=forms.Select(attrs={'class': 'add_adminfilters'}),
                                                                    required=False)
            self.fields[ADMINFILTERS_ADD_PARAM].choices = [('', '')] + self.custom_filter.choices
        
        if self.custom_filters:
            self.fields[ADMINFILTERS_LOAD_PARAM] = forms.ChoiceField(label=_(u'Load preset:'),
                                                                     widget=forms.Select(attrs={'class':'load_adminfilters'}))
            self.fields[ADMINFILTERS_LOAD_PARAM].choices = [('', '')] + [(cf.id, cf.verbose_name) for cf in self.custom_filters]
        
        self.field_rows = []
        
        for query in self.custom_filter.bundled_queries.all():
            query_instance = query.query_instance(None, {}, self.custom_filter.model, None)
            if query_instance:
                row = ['%s_enabled' % query_instance.parameter_name,
                       '%s_criteria' % query_instance.parameter_name]
                self.fields['%s_enabled' % query_instance.parameter_name] = forms.BooleanField(label=query_instance.title.title(),
                                                                            initial=True,
                                                                            required=False,
                                                                            widget=forms.CheckboxInput(attrs={'class':'enable'}))
                
                query_criterias = [(p, t) for (p, t) in query_instance.lookups(None, self.custom_filter.model)]
                self.fields['%s_criteria' % query_instance.parameter_name] = forms.ChoiceField(choices=query_criterias,
                                                                             initial=query.value,
                                                                             required=False,
                                                                             widget=forms.Select(attrs={'class':'criteria'}))
                self.field_rows.append(row)
        for query in list(self.custom_filter.queries.all()) + self.new_fields:
            if not isinstance(query, CustomQuery):
                query = CustomQuery(custom_filter=self.custom_filter, field=query)
            field = DateTimeField()
            if query.model_field:
                row = ['%s_enabled' % query.field,
                       '%s_criteria' % query.field]
                self.fields['%s_enabled' % query.field] = forms.BooleanField(label=query.field_verbose_name,
                                                                            initial=True,
                                                                            required=False,
                                                                            widget=forms.CheckboxInput(attrs={'class':'enable'}))
                if query.criterias:
                    self.fields['%s_criteria' % query.field] = forms.ChoiceField(choices=query.criterias,
                                                                             initial=query.criteria,
                                                                             required=False,
                                                                             widget=forms.Select(attrs={'class':'criteria'}))
                if query.choices:
                    attrs = {'class': 'value'}
                    if query.is_multiple or len(self.params.getlist('%s_value' % query.field, None)) > 1:
                        widget = forms.SelectMultiple(attrs=attrs)
                        value_field = forms.MultipleChoiceField(choices=query.choices,
                                                    initial=query.value,
                                                    widget=widget)
                    else:
                        widget = forms.Select(attrs=attrs)
                        value_field = forms.ChoiceField(choices=query.choices,
                                                    initial=query.value,
                                                    widget=widget)
                        
                elif query.field_type in ['date', 'datetime']:
                    if query.is_multiple:
                        from datetime import datetime
                        value = datetime.now()
                    else:

                        try:
                            value = field.to_python(query.value)
                        except ValidationError:
                            value = field.to_python(query.value[:-7])
                    if query.field_type == 'date':
                        value_field = forms.DateField(initial=value, widget=widgets.AdminDateWidget())
                    elif query.field_type == 'datetime':
                        value_field = forms.DateTimeField(initial=value, widget=widgets.AdminSplitDateTime())
                    dwidget = forms.TextInput(attrs={'style': 'display: %s' % ('block' if query.criteria == 'days_ago' else 'none'),
                                                     'size': 5})
                    dfield = forms.CharField(initial=query.value, 
                                             widget=dwidget,
                                             required=False)
                else:
                    value_field = forms.CharField(initial=query.value, widget=forms.TextInput(attrs={'size':10}))

                if value_field:
                    self.fields['%s_value' % query.field] = value_field
                    row.append('%s_value' % query.field)
                
                if query.field_type in ['date', 'datetime', 'integer']:
                    row.append('%s_start' % query.field)
                    row.append('%s_end' % query.field)
                    self.fields['%s_start' % query.field] = value_field
                    self.fields['%s_end' % query.field] = value_field
                    if query.field_type in ['date', 'datetime']:
                        row.append('%s_dago' % query.field)
                        self.fields['%s_dago' % query.field] = dfield
                    if query.criteria == 'between':
                        default_value = ['', '']
                        bvalue = getattr(query, 'field_value') or default_value
                        self.initial['%s_start' % query.field] = field.to_python(bvalue[0]) if bvalue[0] else None
                        self.initial['%s_end' % query.field] = field.to_python(bvalue[1]) if bvalue[1] else None
                        self.initial['%s_dago' % query.field] = ''
                        self.initial['%s_value' % query.field] = ''
                self.field_rows.append(row)
Beispiel #32
0
    def post(self, request):

        request_data = self.get_request_data(request, "post", {
            "name": "",
            "status": "",
            "datetime": "",
        })

        self.form().add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 200],
                        'error':
                        _('Error! Incident name must be 1 to 200 characters long.'
                          )
                    }
                }
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_datetime': {
                        'error': _('Error! Datetime is invalid.')
                    }
                }
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["open", "closed"]],
                        'error': _('Error! Incident is invalid.')
                    }
                }
            }
        })

        self.form().process()

        if not self.form().is_passed():
            return self.json(self.form().get_errors())

        result = self.__incident.insert_one({
            "name":
            self.form().get_sinput("name"),
            "status":
            self.form().get_sinput("status"),
            "datetime":
            DateTimeField().clean(self.form().get_sinput("datetime")),
            "uri":
            self.__incident.generate_uri(6)
        })

        if result:
            return self.json([{
                "type": "success",
                "message": _("Incident created successfully.")
            }])
        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while creating incident.")
            }])