Exemple #1
0
    def test_dt_from_str(self):
        create_dt = self.create_datetime
        self.assertEqual(
            create_dt(year=2013,
                      month=7,
                      day=25,
                      hour=12,
                      minute=28,
                      second=45), dt_from_str('2013-07-25 12:28:45'))
        self.assertEqual(
            create_dt(year=2013, month=7, day=25, hour=8, utc=True),
            dt_from_str('2013-07-25 11:00:00+03:00'))

        DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS

        def check(fmt, dt_str, **kwargs):
            if fmt in DATETIME_INPUT_FORMATS:
                self.assertEqual(create_dt(**kwargs), dt_from_str(dt_str))
            else:
                print('DatesTestCase: skipped datetime format:', fmt)

        check('%d-%m-%Y', '25/07/2013', year=2013, month=7, day=25)
        check('%Y-%m-%d', '2014-08-26', year=2014, month=8, day=26)

        check('%Y-%m-%dT%H:%M:%S.%fZ',
              '2013-07-25 12:28:45',
              year=2013,
              month=7,
              day=25,
              hour=12,
              minute=28,
              second=45)
Exemple #2
0
 def _get_date(self, date_str):
     if date_str:
         try:
             return dt_from_str(date_str).date()
         except AttributeError:
             logger.warning('CustomDatetimeField => invalid date: %s',
                            date_str)
Exemple #3
0
 def check(fmt, dt_str, **kwargs):
     if fmt in DATETIME_INPUT_FORMATS:
         self.assertEqual(create_dt(**kwargs), dt_from_str(dt_str))
     else:
         print('DatesTestCase: skipped datetime format:', fmt)
Exemple #4
0
    def _create_instance_n_history(self,
                                   data,
                                   user=None,
                                   source='',
                                   action=''):  # TODO: remove 'action'
        is_created = True
        instance = self.model()
        model_get_field = self.model._meta.get_field

        try:
            with atomic():
                for field_name, field_value in [
                        *data.items()
                ]:  # NB: we build a list to modify "data"
                    try:
                        field = model_get_field(field_name)
                    except FieldDoesNotExist:
                        # TODO: data.pop(field_name) when virtual fields are added in crudity,
                        #       because for example user_id is not a "real field" (model._meta.get_field)
                        continue

                    # TODO: exclude not editable fields ??

                    if field_value is None:
                        data[field_name] = field.to_python(None)
                        continue

                    # if isinstance(field_value, basestring) and not isinstance(field_value, unicode):
                    #     field_value = field_value.decode('utf8')

                    if not isinstance(field, TextField) and isinstance(
                            field_value, str):
                        data[field_name] = field_value = field_value.replace(
                            '\n', ' ')

                    if isinstance(field, DateTimeField):
                        data[field_name] = field_value = dt_from_str(
                            field_value.strip())
                    elif isinstance(field, DateField):
                        data[field_name] = field_value = date_from_str(
                            field_value.strip())

                    elif isinstance(field, BooleanField) and isinstance(
                            field_value, str):
                        data[field_name] = field_value = field.to_python(
                            field_value.strip()
                            [0:1].lower())  #Trick to obtain 't'/'f' or '1'/'0'

                    elif isinstance(field, ForeignKey) and issubclass(
                            field.remote_field.model, Document):
                        filename, blob = field_value  # Should be pre-processed by the input
                        upload_path = Document._meta.get_field(
                            'filedata').upload_to.split('/')

                        if user is None:
                            shift_user_id = data.get('user_id')
                            User = get_user_model(
                            )  # TODO: use first() instead
                            if shift_user_id is None:
                                try:
                                    # Not as the default value of data.get because a query is
                                    # always done even the default value is not necessary
                                    shift_user_id = User.objects.filter(
                                        is_superuser=True)[0].id
                                except IndexError:
                                    continue  # There is really nothing we can do
                        else:
                            shift_user_id = user.id

                        doc_entity = Document(
                            user_id=shift_user_id,
                            filedata=handle_uploaded_file(ContentFile(blob),
                                                          path=upload_path,
                                                          name=filename),
                            # folder=Folder.objects.get_or_create(
                            linked_folder=Folder.objects.get_or_create(
                                title=_('External data'),
                                parent_folder=None,
                                defaults={'user_id': shift_user_id},
                            )[0],
                            description=_('Imported from external data.'),
                        )
                        assign_2_charfield(doc_entity, 'title', filename)
                        doc_entity.save()

                        setattr(instance, field_name, doc_entity)
                        data.pop(field_name)
                        continue

                    elif issubclass(
                            field.__class__, FileField
                    ):  # TODO: why not isinstance(field, FileField) ??
                        filename, blob = field_value  # Should be pre-processed by the input
                        upload_path = field.upload_to.split('/')
                        setattr(
                            instance, field_name,
                            handle_uploaded_file(ContentFile(blob),
                                                 path=upload_path,
                                                 name=filename))
                        data.pop(field_name)
                        continue

                    data[field_name] = field.to_python(field_value)
                    # setattr(instance, field_name, field.to_python(field_value)) TODO (instead of for ..: setattr()... ??

                instance.__dict__.update(data)
                # for k, v in data.iteritems(): #TODO: (but fix bug with ManyToManyField)
                # setattr(instance, k, v)

                self._create_instance_before_save(instance, data)
                instance.save()
                need_new_save = self._create_instance_after_save(
                    instance, data)
                if need_new_save:
                    instance.save()

                history = History(
                )  # TODO: History.objects.create(entity=intance [...])
                history.entity = instance
                history.action = 'create'
                history.source = source
                history.user = user
                history.description = _('Creation of {entity}').format(
                    entity=instance)
                history.save()
        except IntegrityError as e:
            logger.error(
                '_create_instance_n_history() : error when try to create instance [%s]',
                e)
            is_created = False

        return is_created, instance