Example #1
0
File: demo.py Project: DarioGT/lino
def objects():

    Member = rt.modules.households.Member
    MemberRoles = rt.modules.households.MemberRoles
    # Household = resolve_model('households.Household')
    Person = resolve_model(dd.plugins.households.person_model)
    Type = resolve_model('households.Type')

    MEN = Cycler(Person.objects.filter(gender=dd.Genders.male).order_by('-id'))
    WOMEN = Cycler(
        Person.objects.filter(gender=dd.Genders.female).order_by('-id'))
    TYPES = Cycler(Type.objects.all())

    ses = rt.login()
    for i in range(5):
        pv = dict(head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop())
        ses.run(Person.create_household, action_param_values=pv)
        # yield ses.response['data_record']
        # he = MEN.pop()
        # she = WOMEN.pop()

        # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3)
        # yield fam
        # yield Member(household=fam, person=he, role=Role.objects.get(pk=1))
        # yield Member(household=fam, person=she, role=Role.objects.get(pk=2))

    i = 0
    for m in Member.objects.filter(role=MemberRoles.head):
        i += 1
        if i % 3 == 0:
            m.end_date = i2d(20020304)
            yield m

            pv = dict(head=m.person, partner=WOMEN.pop(), type=TYPES.pop())
            ses.run(Person.create_household, action_param_values=pv)
Example #2
0
def objects():
    Sector = resolve_model('cbss.Sector')
    #~ for ln in SECTORS.splitlines():
        #~ if ln:
            #~ a = ln.split(None,1)
            #~ labels = [s.strip() for s in a[1].split('|')]
            #~ if len(labels) != 3:
                #~ raise Exception("Line %r : labels is %r" %(ln,labels))
            #~ if not labels[2]:
                #~ labels[2] = labels[0]
            #~ yield Sector(code=int(a[0]),**babel_values('name',fr=labels[0],nl=labels[1],de=labels[2]))

    Purpose = resolve_model('cbss.Purpose')
    for ln in PURPOSES.splitlines():
        if ln:
            a = ln.split(None, 2)
            #~ assert a[0] in ('*', '17')
            sc = a[0]
            if sc == '*':
                sc = None
            else:
                #~ sector = Sector.objects.get(code=int(sc))
                sc = int(sc)
            labels = [s.strip() for s in a[2].split('|')]
            if len(labels) == 2:
                labels.append(labels[0])
            elif len(labels) != 3:
                raise Exception("Line %r : labels is %r" % (ln, labels))
            yield Purpose(sector_code=sc, code=int(a[1]), **babel_values('name', en=labels[0], fr=labels[0], nl=labels[1], de=labels[2]))
Example #3
0
 def on_site_startup(self, site):
     from lino.core.utils import resolve_model
     self.item_model = resolve_model(self.item_model)
     # ivm = self.item_model._meta.get_field('voucher').remote_field.model
     # if self.voucher_model != ivm:
     #     raise Exception("voucher_model is {} but should be {}".format(
     #         self.voucher_model, ivm))
     self.voucher_model = resolve_model(self.voucher_model)
Example #4
0
File: std.py Project: sandeez/lino
def objects():

    #~ yield companyType('Firma','Firma')
    #~ yield companyType('asbl','asbl')
    #~ yield companyType('A.S.B.L.','A.S.B.L.')
    #~ yield companyType('sprl','sprl')
    #~ yield companyType('GmbH','GmbH')
    #~ yield companyType('AG','AG')
    #~ yield companyType('S.A.','S.A.')
    #~ yield companyType('S.C.','S.C.')
    #~ yield companyType('V.o.G.','V.o.G.')
    #~ yield companyType('G.o.E.','G.o.E.')
    #~ yield companyType('A.S.B.L.','Association sans but lucratif')
    #~ yield companyType('Maison','Maison')
    #~ yield companyType('Fachklinik','Fachklinik')
    #~ yield companyType("Centre d'Accueil d'Urgence","Centre d'Accueil d'Urgence")

    #~ yield companyType(**babel_values('name',
        #~ en=u"Public Limited Company",
        #~ nl=u'NV (Naamloze Vennootschap)',
        #~ fr=u'SA (Société Anonyme)',
        #~ de=u"AG (Aktiengesellschaft)"))

    for ct in COMPANY_TYPES:
        yield companyType(**ct)

    yield roletype(**babel_values('name', en="Manager", fr='Gérant', de="Geschäftsführer", et="Tegevjuht"))
    yield roletype(**babel_values('name', en="Director", fr='Directeur', de="Direktor", et="Direktor"))
    yield roletype(**babel_values('name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär"))
    yield roletype(**babel_values('name', en="IT Manager", fr='Gérant informatique', de="EDV-Manager", et="IT manager"))
    yield roletype(**babel_values('name', en="President", fr='Président', de="Präsident", et="President"))

    if settings.SITE.is_installed('contenttypes'):

        from django.contrib.contenttypes.models import ContentType

        I = Instantiator('gfks.HelpText',
                         'content_type field help_text').build

        Person = resolve_model("contacts.Person")
        t = ContentType.objects.get_for_model(Person)

        #~ yield I(t,'birth_date',u"""\
    #~ Unkomplette Geburtsdaten sind erlaubt, z.B.
    #~ <ul>
    #~ <li>00.00.1980 : irgendwann in 1980</li>
    #~ <li>00.07.1980 : im Juli 1980</li>
    #~ <li>23.07.0000 : Geburtstag am 23. Juli, Alter unbekannt</li>
    #~ </ul>
    #~ """)

        Partner = resolve_model('contacts.Partner')
        t = ContentType.objects.get_for_model(Partner)
        yield I(t, 'language', u"""\
    Die Sprache, in der Dokumente ausgestellt werden sollen.
    """)
Example #5
0
def objects():

    pcsw = dd.resolve_app('pcsw')

    Place = resolve_model('countries.Place')
    Client = resolve_model('pcsw.Client')
    CourseContent = resolve_model('courses.CourseContent')

    CLIENTS = Cycler(
        Client.objects.filter(client_state=pcsw.ClientStates.coached))

    eupen = Place.objects.get(name__exact='Eupen')

    courseprovider = Instantiator('courses.CourseProvider').build
    oikos = courseprovider(name=u"Oikos", city=eupen, country='BE')
    yield oikos
    # oikos.repairdata()

    kap = courseprovider(name=u"KAP", city=eupen, country='BE')
    yield kap
    # kap.repairdata()

    yield CourseContent(id=1, name=u"Deutsch")
    yield CourseContent(id=2, name=u"Französisch")

    COURSECONTENTS = Cycler(CourseContent.objects.all())

    creq = Instantiator('courses.CourseRequest').build
    for i in range(20):
        yield creq(
            person=CLIENTS.pop(), content=COURSECONTENTS.pop(),
            date_submitted=settings.SITE.demo_date(-i * 2))
    #~ yield creq(person=ulrike,content=1,date_submitted=settings.SITE.demo_date(-30))
    #~ yield creq(person=tatjana,content=1,date_submitted=settings.SITE.demo_date(-30))
    #~ yield creq(person=erna,content=2,date_submitted=settings.SITE.demo_date(-30))

    offer = Instantiator('courses.CourseOffer').build
    course = Instantiator('courses.Course').build
    yield offer(provider=oikos, title=u"Deutsch für Anfänger", content=1)
    #~ yield course(offer=1,start_date=i2d(20110110))
    yield course(offer=1, start_date=settings.SITE.demo_date(+30))

    yield offer(provider=kap, title=u"Deutsch für Anfänger", content=1)
    #~ yield course(offer=2,start_date=i2d(20110117))
    yield course(offer=2, start_date=settings.SITE.demo_date(+16))

    yield offer(provider=kap, title=u"Français pour débutants", content=2)
    #~ yield course(offer=3,start_date=i2d(20110124))
    yield course(offer=3, start_date=settings.SITE.demo_date(+16))
Example #6
0
def setup_params_choosers(self):
    if self.parameters:
        for k, fld in list(self.parameters.items()):
            if isinstance(fld, models.ForeignKey):
                # Before Django 1.8:
                if AFTER18:
                    fld.rel.model = resolve_model(fld.rel.model)
                else:
                    fld.rel.to = resolve_model(fld.rel.to)
                from lino.core.kernel import set_default_verbose_name
                set_default_verbose_name(fld)
                #~ if fld.verbose_name is None:
                    #~ fld.verbose_name = fld.rel.model._meta.verbose_name

            check_for_chooser(self, fld)
Example #7
0
def setup_params_choosers(self):
    if self.parameters:
        for k, fld in list(self.parameters.items()):
            if isinstance(fld, models.ForeignKey):
                # Before Django 1.8:
                if AFTER18:
                    fld.rel.model = resolve_model(fld.rel.model)
                else:
                    fld.rel.to = resolve_model(fld.rel.to)
                from lino.core.kernel import set_default_verbose_name
                set_default_verbose_name(fld)
                #~ if fld.verbose_name is None:
                    #~ fld.verbose_name = fld.rel.model._meta.verbose_name

            check_for_chooser(self, fld)
Example #8
0
    def migrate_from_0_0_4(self, globals_dict):
        """
        - removed field User.notifyme_mode
        
        """

        # bv2kw = globals_dict['bv2kw']
        # new_content_type_id = globals_dict['new_content_type_id']
        # cal_EventType = resolve_model("cal.EventType")
        users_User = resolve_model("users.User")
        
        @override(globals_dict)
        def create_users_user(id, modified, created, username, password, profile, initials, first_name, last_name, email, remarks, language, partner_id, access_class, event_type_id, notifyme_mode):
            if profile: profile = settings.SITE.modules.users.UserTypes.get_by_value(profile)
            if access_class: access_class = settings.SITE.modules.cal.AccessClasses.get_by_value(access_class)
            kw = dict()
            kw.update(id=id)
            kw.update(modified=modified)
            kw.update(created=created)
            kw.update(username=username)
            kw.update(password=password)
            kw.update(profile=profile)
            kw.update(initials=initials)
            kw.update(first_name=first_name)
            kw.update(last_name=last_name)
            kw.update(email=email)
            kw.update(remarks=remarks)
            kw.update(language=language)
            kw.update(partner_id=partner_id)
            kw.update(access_class=access_class)
            kw.update(event_type_id=event_type_id)
            # kw.update(notifyme_mode=notifyme_mode)
            return users_User(**kw)
        
        return '2016.12.0'
Example #9
0
    def class_init(cls):
        """Called internally at site startup. Don't override.

        """
        # if str(cls) == 'courses.Pupils':
        #     print("20160329 class_init")
        if hasattr(cls, 'required'):
            raise ChangedAPI(
                "{0} must convert `required` to `required_roles`".format(cls))
        master = getattr(cls, 'master', None)
        if isinstance(master, string_types):
            cls.master = resolve_model(master)

        actions.install_layout(cls, 'detail_layout', layouts.DetailLayout)
        actions.install_layout(
            cls, 'insert_layout', layouts.InsertLayout,
            window_size=(cls.insert_layout_width, 'auto'))

        if cls.parameters is None:
            params = cls.get_parameter_fields()
            if len(params):
                cls.parameters = params
        else:
            cls.parameters = cls.get_parameter_fields(**cls.parameters)

        cls.simple_parameters = cls.get_simple_parameters()
Example #10
0
 def migrate_from_0_0_1(globals_dict):
     """
     - Renamed `countries.City` to `countries.Place`
     """
     countries_Place = resolve_model("countries.Place")
     globals_dict.update(countries_City=countries_Place)
     return '0.0.2'
Example #11
0
    def class_init(cls):
        """Called internally at site startup. Don't override.

        """
        # if str(cls) == 'courses.Pupils':
        #     print("20160329 class_init")
        if hasattr(cls, 'required'):
            raise ChangedAPI(
                "{0} must convert `required` to `required_roles`".format(cls))
        master = getattr(cls, 'master', None)
        if isinstance(master, string_types):
            cls.master = resolve_model(master)

        actions.install_layout(cls, 'detail_layout', layouts.DetailLayout)
        actions.install_layout(cls,
                               'insert_layout',
                               layouts.InsertLayout,
                               window_size=(cls.insert_layout_width, 'auto'))

        if cls.parameters is None:
            params = cls.get_parameter_fields()
            if len(params):
                cls.parameters = params
        else:
            cls.parameters = cls.get_parameter_fields(**cls.parameters)

        cls.simple_parameters = cls.get_simple_parameters()
Example #12
0
    def __init__(self,
                 model=None,
                 watched_fields=None,
                 created_tpl=None,
                 updated_tpl=None,
                 deleted_tpl=None,
                 master_field=None):
        """

        """
        if model:
            self.model = model
        if watched_fields:
            self.watched_fields = watched_fields
        self.model = resolve_model(self.model, strict=True)
        self.watched_fields = fields_list(self.model, self.watched_fields)
        if master_field:
            self.master_field = master_field

        for k in ('created_tpl', 'updated_tpl', 'deleted_tpl'):
            v = locals().get(k)
            if v:
                setattr(self, k, v)
            v = getattr(self, k)
            if v:
                setattr(self, k, rt.get_template(v))
Example #13
0
    def lino_resolve_type(self):
        """
        Called on every virtual field when all models are loaded.
        """

        f = self.return_type

        if isinstance(f, six.string_types):
            f = self.return_type = resolve_field(f)

        if isinstance(f, FakeField):
            sortable_by = f.sortable_by
            self.sortable_by = sortable_by
            if sortable_by and isinstance(sortable_by, list):
                sortable_by = sortable_by[0]
            self.column = sortable_by

        if isinstance(f, models.ForeignKey):
            f.remote_field.model = resolve_model(f.remote_field.model)
            set_default_verbose_name(f)

        for k in VFIELD_ATTRIBS:
            setattr(self, k, getattr(f, k, None))

        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type 1 %s on %s',
        #                 self.name, self.verbose_name)

        #~ removed 20120919 self.return_type.editable = self.editable
        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type done %s %s',
        #                 self.name, self.verbose_name)

        from lino.core import store
        store.get_atomizer(self.model, self, self.name)
Example #14
0
    def lino_resolve_type(self):
        """
        Called on every virtual field when all models are loaded.
        """

        f = self.return_type

        if isinstance(f, six.string_types):
            f = self.return_type = resolve_field(f)

        if isinstance(f, FakeField):
            sortable_by = f.sortable_by
            self.sortable_by = sortable_by
            if sortable_by and isinstance(sortable_by, list):
                sortable_by = sortable_by[0]
            self.column = sortable_by

        if isinstance(f, models.ForeignKey):
            f.remote_field.model = resolve_model(f.remote_field.model)
            set_default_verbose_name(f)

        for k in VFIELD_ATTRIBS:
            setattr(self, k, getattr(f, k, None))

        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type 1 %s on %s',
        #                 self.name, self.verbose_name)

        #~ removed 20120919 self.return_type.editable = self.editable
        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type done %s %s',
        #                 self.name, self.verbose_name)

        from lino.core import store
        store.get_atomizer(self.model, self, self.name)
Example #15
0
def objects():

    Member = rt.modules.households.Member
    MemberRoles = rt.modules.households.MemberRoles
    # Household = resolve_model('households.Household')
    Person = resolve_model(dd.plugins.households.person_model)
    Type = resolve_model('households.Type')

    MEN = Cycler(Person.objects.filter(gender=dd.Genders.male)
                 .order_by('-id'))
    WOMEN = Cycler(Person.objects.filter(gender=dd.Genders.female)
                   .order_by('-id'))
    TYPES = Cycler(Type.objects.all())

    ses = rt.login()
    for i in range(5):
        pv = dict(
            head=MEN.pop(), partner=WOMEN.pop(),
            type=TYPES.pop())
        ses.run(
            Person.create_household,
            action_param_values=pv)
        # yield ses.response['data_record']
        # he = MEN.pop()
        # she = WOMEN.pop()
        
        # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3)
        # yield fam
        # yield Member(household=fam, person=he, role=Role.objects.get(pk=1))
        # yield Member(household=fam, person=she, role=Role.objects.get(pk=2))

    i = 0
    for m in Member.objects.filter(role=MemberRoles.head):
        i += 1
        if i % 3 == 0:
            m.end_date = i2d(20020304)
            yield m

            pv = dict(
                head=m.person, partner=WOMEN.pop(),
                type=TYPES.pop())
            ses.run(
                Person.create_household,
                action_param_values=pv)
Example #16
0
def create_and_get(model, **kw):
    """
    Instantiate, full_clean, save 
    and read back from database (the latter to avoid certain Django side effects)
    """
    model = resolve_model(model)
    o = model(**kw)
    o.full_clean()
    o.save()
    return model.objects.get(pk=o.pk)
Example #17
0
def create_and_get(model, **kw):
    """
    Instantiate, full_clean, save 
    and read back from database (the latter to avoid certain Django side effects)
    """
    model = resolve_model(model)
    o = model(**kw)
    o.full_clean()
    o.save()
    return model.objects.get(pk=o.pk)
Example #18
0
    def migrate_from_0_0_1(self, globals_dict):
        """
        - Renamed `countries.City` to `countries.Place`
        - removed field imode from contacts.Partner
        - renamed sales.PaymentTerm to vat.PaymentTerm
        """
        countries_Place = resolve_model("countries.Place")
        globals_dict.update(countries_City=countries_Place)

        globals_dict.update(
            sales_PaymentTerm=resolve_model("vat.PaymentTerm"))

        contacts_Partner = resolve_model("contacts.Partner")
        def create_contacts_partner(id, country_id, city_id, region_id, zip_code, name, addr1, street_prefix, street, street_no, street_box, addr2, language, email, url, phone, gsm, fax, remarks, invoicing_address_id, payment_term_id, vat_regime, imode_id):
            kw = dict()
            kw.update(id=id)
            kw.update(country_id=country_id)
            kw.update(city_id=city_id)
            kw.update(region_id=region_id)
            kw.update(zip_code=zip_code)
            kw.update(name=name)
            kw.update(addr1=addr1)
            kw.update(street_prefix=street_prefix)
            kw.update(street=street)
            kw.update(street_no=street_no)
            kw.update(street_box=street_box)
            kw.update(addr2=addr2)
            kw.update(language=language)
            kw.update(email=email)
            kw.update(url=url)
            kw.update(phone=phone)
            kw.update(gsm=gsm)
            kw.update(fax=fax)
            kw.update(remarks=remarks)
            kw.update(invoicing_address_id=invoicing_address_id)
            kw.update(payment_term_id=payment_term_id)
            kw.update(vat_regime=vat_regime)
            # kw.update(imode_id=imode_id)
            return contacts_Partner(**kw)
        globals_dict.update(create_contacts_partner=create_contacts_partner)

        return '0.0.2'
Example #19
0
File: demo.py Project: TonisPiip/xl
def objects():

    Member = rt.modules.households.Member
    MemberRoles = rt.modules.households.MemberRoles
    # Household = resolve_model('households.Household')
    Person = dd.plugins.households.person_model
    Type = resolve_model('households.Type')

    men = Person.objects.filter(gender=dd.Genders.male).order_by('-id')
    women = Person.objects.filter(gender=dd.Genders.female).order_by('-id')
    # avoid interference with persons created by humanlinks demo
    # because these have already their households:
    men = men.filter(household_members__isnull=True)
    men = men.filter(humanlinks_children__isnull=True)
    men = men.filter(humanlinks_parents__isnull=True)
    women = women.filter(humanlinks_children__isnull=True)
    women = women.filter(humanlinks_parents__isnull=True)
    women = women.filter(household_members__isnull=True)

    MEN = Cycler(men)
    WOMEN = Cycler(women)
    TYPES = Cycler(Type.objects.all())

    if not len(MEN) or not len(WOMEN):
        raise Exception("Not enough persons in {} and {} (all: {})".format(
            men, women, Person.objects.all()))

    # avoid automatic creation of children
    # loading_from_dump = settings.SITE.loading_from_dump
    # settings.SITE.loading_from_dump = True
    ses = rt.login()
    for i in range(5):
        pv = dict(head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop())
        ses.run(Person.create_household, action_param_values=pv)
        # yield ses.response['data_record']
        # he = MEN.pop()
        # she = WOMEN.pop()

        # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3)
        # yield fam
        # yield Member(household=fam, person=he, role=Role.objects.get(pk=1))
        # yield Member(household=fam, person=she, role=Role.objects.get(pk=2))

    i = 0
    for m in Member.objects.filter(role=MemberRoles.head):
        i += 1
        if i % 3 == 0:
            m.end_date = i2d(20020304)
            yield m

            pv = dict(head=m.person, partner=WOMEN.pop(), type=TYPES.pop())
            ses.run(Person.create_household, action_param_values=pv)
Example #20
0
def setup_params_choosers(self):
    if self.parameters:
        for k, fld in self.parameters.items():
            if isinstance(fld, models.ForeignKey):
                msg = "Invalid target %s in parameter {} of {}".format(k, self)
                fld.remote_field.model = resolve_model(fld.remote_field.model,
                                                       strict=msg)
                from lino.core.kernel import set_default_verbose_name
                set_default_verbose_name(fld)
                #~ if fld.verbose_name is None:
                #~ fld.verbose_name = fld.remote_field.model._meta.verbose_name

            check_for_chooser(self, fld)
Example #21
0
    def lino_resolve_type(self):
        """Called on virtual fields that are defined on an Actor

        """
        # ~ logger.info("20120903 lino_resolve_type %s.%s", actor_or_model, name)
        # ~ if self.name is not None:
        # ~ if self.name != name:
        # ~ raise Exception("Tried to re-use %s.%s" % (actor_or_model,name))
        # ~ self.name = name

        if isinstance(self.return_type, basestring):
            self.return_type = resolve_field(self.return_type)

        # ~ self.return_type.name = self.name
        if isinstance(self.return_type, models.ForeignKey):
            f = self.return_type
            if AFTER18:
                f.rel.model = resolve_model(f.rel.model)
            else:
                f.rel.to = resolve_model(f.rel.to)
            if f.verbose_name is None:
                # ~ if f.name is None:
                f.verbose_name = f.rel.model._meta.verbose_name
                # ~ from lino.core.kernel import set_default_verbose_name
                # ~ set_default_verbose_name(self.return_type)

        # ~ removed 20120919 self.return_type.editable = self.editable
        for k in """to_python choices save_form_data
          value_to_string verbose_name max_length rel
          max_digits decimal_places
          help_text
          blank""".split():
            setattr(self, k, getattr(self.return_type, k, None))
        # ~ logger.info('20120831 VirtualField %s on %s',name,actor_or_model)

        from lino.core import store

        # ~ self._lino_atomizer = store.create_field(self,self.name)
        store.get_atomizer(self.model, self, self.name)
Example #22
0
    def lino_resolve_type(self):
        """Called on virtual fields that are defined on an Actor

        """
        #~ logger.info("20120903 lino_resolve_type %s.%s", actor_or_model, name)
        #~ if self.name is not None:
        #~ if self.name != name:
        #~ raise Exception("Tried to re-use %s.%s" % (actor_or_model,name))
        #~ self.name = name

        if isinstance(self.return_type, six.string_types):
            self.return_type = resolve_field(self.return_type)

        #~ self.return_type.name = self.name
        if isinstance(self.return_type, models.ForeignKey):
            f = self.return_type
            if AFTER18:
                f.rel.model = resolve_model(f.rel.model)
            else:
                f.rel.to = resolve_model(f.rel.to)
            if f.verbose_name is None:
                #~ if f.name is None:
                f.verbose_name = f.rel.model._meta.verbose_name
                #~ from lino.core.kernel import set_default_verbose_name
                #~ set_default_verbose_name(self.return_type)

        #~ removed 20120919 self.return_type.editable = self.editable
        for k in ('''to_python choices save_form_data
          value_to_string verbose_name max_length rel
          max_digits decimal_places
          help_text
          blank'''.split()):
            setattr(self, k, getattr(self.return_type, k, None))
        #~ logger.info('20120831 VirtualField %s on %s',name,actor_or_model)

        from lino.core import store
        #~ self._lino_atomizer = store.create_field(self,self.name)
        store.get_atomizer(self.model, self, self.name)
Example #23
0
    def __init__(self, model, fieldnames=None, converter_classes={}, **kw):
        # self.model = resolve_model(model,strict=True)
        self.model = resolve_model(model)
        if isinstance(self.model, UnresolvedModel):
            raise Exception("Instantiator on unresolved model %s", model)
        if not self.is_active():

            def noop(*values, **kw):
                pass

            self.build = noop
            return
        # if self.model._meta.pk is None:
        # raise Exception("Model %r is not installed (_meta.pk is None)." % self.model)
        # if type(fieldnames) == str:
        if isinstance(fieldnames, six.string_types):
            fieldnames = fieldnames.split()
        self.default_values = kw
        #self.fieldnames = fieldnames
        lookup_fields = {}
        self.converters = []
        if fieldnames is None:
            self.fields = self.model._meta.fields
        else:
            self.fields = []
            for name in fieldnames:
                a = name.split(":")
                if len(a) == 2:
                    name = a[0]
                    lookup_fields[name] = a[1]

                rf = make_remote_field(model, name)
                if rf:
                    self.fields.append(rf)
                else:
                    field = self.model._meta.get_field(name)
                    self.fields.append(field)
        # print " ".join(dir(model_class))
        # print " ".join(model_class._meta.fields)
        # for f in model_class._meta.fields:
        # for f in self.fields:
        for f in self.model._meta.fields + self.model._meta.many_to_many:
            cv = None
            cvc = converter_classes.get(f.name, None)
            if cvc is not None:
                cv = cvc(f)
            else:
                cv = make_converter(f, lookup_fields)
            if cv is not None:
                self.converters.append(cv)
Example #24
0
    def __init__(self, model, fieldnames=None, converter_classes={}, **kw):
        # self.model = resolve_model(model,strict=True)
        self.model = resolve_model(model)
        if isinstance(self.model, UnresolvedModel):
            raise Exception("Instantiator on unresolved model %s", model)
        if not self.is_active():
            def noop(*values, **kw):
                pass
            self.build = noop
            return
        # if self.model._meta.pk is None:
            # raise Exception("Model %r is not installed (_meta.pk is None)." % self.model)
        # if type(fieldnames) == str:
        if isinstance(fieldnames, six.string_types):
            fieldnames = fieldnames.split()
        self.default_values = kw
        #self.fieldnames = fieldnames
        lookup_fields = {}
        self.converters = []
        if fieldnames is None:
            self.fields = self.model._meta.fields
        else:
            self.fields = []
            for name in fieldnames:
                a = name.split(":")
                if len(a) == 2:
                    name = a[0]
                    lookup_fields[name] = a[1]

                rf = make_remote_field(model, name)
                if rf:
                    self.fields.append(rf)
                else:
                    field = self.model._meta.get_field(name)
                    self.fields.append(field)
        # print " ".join(dir(model_class))
        # print " ".join(model_class._meta.fields)
        # for f in model_class._meta.fields:
        # for f in self.fields:
        for f in self.model._meta.fields + self.model._meta.many_to_many:
            cv = None
            cvc = converter_classes.get(f.name, None)
            if cvc is not None:
                cv = cvc(f)
            else:
                cv = make_converter(f, lookup_fields)
            if cv is not None:
                self.converters.append(cv)
Example #25
0
def inject_quick_add_buttons(model, name, target):
    """
    Injects a virtual display field `name` into the specified `model`.
    This field will show up to three buttons
    `[New]` `[Show last]` `[Show all]`.
    `target` is the table that will run these actions.
    It must be a slave of `model`.
    """

    def fn(self, ar):
        if ar is None:
            return ""
        return ar.renderer.quick_add_buttons(ar.spawn(target, master_instance=self))

    tm = resolve_model(target.model)
    inject_field(model, name, fields.VirtualField(fields.DisplayField(tm._meta.verbose_name_plural), fn))
Example #26
0
    def lino_resolve_type(self):
        """
        Called on every virtual field when all models are loaded.
        """

        f = self.return_type

        if isinstance(f, str):
            try:
                f = self.return_type = resolve_field(f)
            except Exception as e:
                raise Exception(
                    "Invalid return type spec {} for {} : {}".format(f, self, e))

        if isinstance(f, FakeField):
            sortable_by = f.sortable_by
            self.sortable_by = sortable_by
            if sortable_by and isinstance(sortable_by, list):
                sortable_by = sortable_by[0]
            self.column = sortable_by

        if isinstance(f, models.ForeignKey):
            f.remote_field.model = resolve_model(f.remote_field.model)
            set_default_verbose_name(f)
            self.get_lookup = f.remote_field.get_lookup  # 20200425
            self.get_path_info = f.remote_field.get_path_info  # 20200425
            self.remote_field = f.remote_field

        for k in VFIELD_ATTRIBS:
            setattr(self, k, getattr(f, k, None))

        # copy help_text if it hasn't been set by help_texts_extractor
        if f.help_text and not self.help_text:
            self.help_text = f.help_text

        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type 1 %s on %s',
        #                 self.name, self.verbose_name)

        #~ removed 20120919 self.return_type.editable = self.editable
        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type done %s %s',
        #                 self.name, self.verbose_name)

        from lino.core import store
        store.get_atomizer(self.model, self, self.name)
Example #27
0
def inject_quick_add_buttons(model, name, target):
    """
    Injects a virtual display field `name` into the specified `model`.
    This field will show up to three buttons
    `[New]` `[Show last]` `[Show all]`.
    `target` is the table that will run these actions.
    It must be a slave of `model`.
    """

    def fn(self, ar):
        if ar is None:
            return ''
        return ar.renderer.quick_add_buttons(
            ar.spawn(target, master_instance=self))
    tm = resolve_model(target.model)
    inject_field(model, name,
                 fields.VirtualField(fields.DisplayField(
                     tm._meta.verbose_name_plural), fn))
Example #28
0
def objects():

    Sector = resolve_model('cbss.Sector')

    fn = join(dirname(__file__), 'lijst_van_sectoren_liste_des_secteurs.csv')
    reader = ucsv.UnicodeReader(
        open(fn, 'r'), encoding='latin1', delimiter=';')

    headers = reader.next()
    if headers != [u'Sector', u'', u'verkorte naam', u'Omschrijving', u'Abréviation', u'Nom']:
        raise Exception("Invalid file format: %r" % headers)
    reader.next()  # ignore second header line
    code = None
    for row in reader:
        s0 = row[0].strip()
        s1 = row[1].strip()
        if s0 or s1:
            kw = {}
            if len(s0) > 0:
                code = int(s0)
            kw.update(code=code)
            if row[1]:
                kw.update(subcode=int(row[1]))
            kw.update(
                **dd.babelkw(
                    'name', de=row[5], fr=row[5], nl=row[3], en=row[5]))
            kw.update(
                **dd.babelkw(
                    'abbr', de=row[4], fr=row[4], nl=row[2], en=row[4]))
            yield Sector(**kw)

    info = settings.SITE.get_language_info('de')
    if info:
        for code, subcode, abbr, name in GERMAN:
            sect = Sector.objects.get(code=code, subcode=subcode)
            if info.index == 0:
                sect.abbr = abbr
                sect.name = name
            else:
                sect.abbr_de = abbr
                sect.name_de = name
            sect.save()
Example #29
0
    def __init__(self, model=None, watched_fields=None,
                 created_tpl=None, updated_tpl=None, deleted_tpl=None,
                 master_field=None):
        """

        """
        if model:
            self.model = model
        if watched_fields:
            self.watched_fields = watched_fields
        self.model = resolve_model(self.model, strict=True)
        self.watched_fields = fields_list(self.model, self.watched_fields)
        if master_field:
            self.master_field = master_field

        for k in ('created_tpl', 'updated_tpl', 'deleted_tpl'):
            v = locals().get(k)
            if v:
                setattr(self, k, v)
            v = getattr(self, k)
            if v:
                setattr(self, k, rt.get_template(v))
Example #30
0
    def lino_resolve_type(self):
        """Called on virtual fields that are defined on an Actor

        """
        #~ logger.info("20120903 lino_resolve_type %s.%s", actor_or_model, name)
        #~ if self.name is not None:
        #~ if self.name != name:
        #~ raise Exception("Tried to re-use %s.%s" % (actor_or_model,name))
        #~ self.name = name

        if isinstance(self.return_type, six.string_types):
            self.return_type = resolve_field(self.return_type)

        f = self.return_type
        #~ self.return_type.name = self.name
        if isinstance(f, models.ForeignKey):
            f.remote_field.model = resolve_model(f.remote_field.model)
            if f.verbose_name is None:
                #~ if f.name is None:
                f.verbose_name = f.remote_field.model._meta.verbose_name
                #~ from lino.core.kernel import set_default_verbose_name
                #~ set_default_verbose_name(self.return_type)

        if isinstance(f, FakeField):
            self.sortable_by = f.sortable_by
        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type 1 %s on %s',
        #                 self.name, self.verbose_name)

        #~ removed 20120919 self.return_type.editable = self.editable
        for k in VFIELD_ATTRIBS:
            setattr(self, k, getattr(self.return_type, k, None))
        # if self.name == 'detail_pointer':
        #     logger.info('20170905 resolve_type done %s %s',
        #                 self.name, self.verbose_name)

        from lino.core import store
        #~ self._lino_atomizer = store.create_field(self,self.name)
        store.get_atomizer(self.model, self, self.name)
Example #31
0

from lino.utils import join_words
from lino_xl.lib.contacts.utils import name2kw, street2kw
#~ from lino_xl.lib.contacts.models import GENDER_MALE, GENDER_FEMALE
from lino.api import dd, rt
from lino.utils.instantiator import Instantiator

from lino.core.utils import resolve_model, obj2str
import lino

from lino.utils import confirm, iif
from lino.core.utils import app_labels
from lino_book.projects.crl.models import CRL

Country = resolve_model('countries.Country')
Place = resolve_model('countries.Place')
Person = resolve_model("contacts.Person")
Company = resolve_model("contacts.Company")


def parsedate(T):
    if not T:
        return
    T = T.replace('.', '')
    try:
        if len(T) == 4:
            return (datetime.date(int(T), 6, 30), True)
        elif len(T) == 6:
            return (datetime.date(int(T[:4]), int(T[4:6]), 15), True)
        elif len(T) == 8:
Example #32
0
def objects():
    # ~ dblogger.info("Installing contacts demo fixture") # use --verbosity=2
    User = resolve_model(settings.SITE.user_model)
    Company = resolve_model("contacts.Company")
    Session = resolve_model('tickets.Session')
    #~ u = User.objects.get(username='******')
    u = User.objects.all()[0]

    rumma = Company.objects.get(name=u'Rumma & Ko OÜ')

    project = Instantiator('tickets.Project', "name", user=u).build
    yield project("TIM")
    lino = project("Lino")
    yield lino
    presto = project("Presto", parent=lino)
    yield presto
    cbss = project("CBSS connection", parent=lino)
    yield cbss

    milestone = Instantiator(
        'tickets.Milestone', "label reached", project=lino).build
    yield milestone('1.4.3', i2d(20120328))
    yield milestone('1.4.5', i2d(20120716))
    yield milestone('1.4.7', i2d(20120717))
    yield milestone('1.4.8', i2d(20120722))
    yield milestone('1.4.9', None)

    ticket = Instantiator('tickets.Ticket', "summary",
                          user=u, project=presto, partner=rumma).build
    presto_proto = ticket(summary="write a first prototype", project=presto)
    yield presto_proto

    #~ session = Instantiator('tickets.Session',"description",user=u,ticket=t).build
    yield Session(date=i2d(20111113),
                  user=u, ticket=presto_proto, start_time='21:45', end_time='23:28',
        description="""\
Created new module (tested in `lino_local.luc`).
Tried first with EventsByTicket instead of Comments,
but Comments are not usually planned.""")
    yield Session(date=i2d(20120603),
                  user=u, ticket=presto_proto, start_time='21:45', end_time='23:28',
        description="""\
replaced Comment by Session.
""")

    yield Session(date=i2d(20120604),
                  user=u, ticket=presto_proto, start_time='08:10', end_time='10:30',
        description="""\
labels, titles, tidy up, EntriesBySession.
""")

    yield Session(date=i2d(20120629),
                  user=u, ticket=presto_proto, start_time='00:05', end_time='01:15',
        description="""\
ProjectsByPartner
""")

    yield Session(date=i2d(20120727),
                  user=u, ticket=presto_proto, start_time='02:30', end_time='03:15',
        description="""\
TicketsByPartner
""")
Example #33
0
def objects():
    # ~ dblogger.info("Installing contacts demo fixture") # use --verbosity=2
    User = resolve_model(settings.SITE.user_model)
    Company = resolve_model("contacts.Company")
    Session = resolve_model('tickets.Session')
    #~ u = User.objects.get(username='******')
    u = User.objects.all()[0]

    rumma = Company.objects.get(name=u'Rumma & Ko OÜ')

    project = Instantiator('tickets.Project', "name", user=u).build
    yield project("TIM")
    lino = project("Lino")
    yield lino
    presto = project("Presto", parent=lino)
    yield presto
    cbss = project("CBSS connection", parent=lino)
    yield cbss

    milestone = Instantiator('tickets.Milestone',
                             "label reached",
                             project=lino).build
    yield milestone('1.4.3', i2d(20120328))
    yield milestone('1.4.5', i2d(20120716))
    yield milestone('1.4.7', i2d(20120717))
    yield milestone('1.4.8', i2d(20120722))
    yield milestone('1.4.9', None)

    ticket = Instantiator('tickets.Ticket',
                          "summary",
                          user=u,
                          project=presto,
                          partner=rumma).build
    presto_proto = ticket(summary="write a first prototype", project=presto)
    yield presto_proto

    #~ session = Instantiator('tickets.Session',"description",user=u,ticket=t).build
    yield Session(date=i2d(20111113),
                  user=u,
                  ticket=presto_proto,
                  start_time='21:45',
                  end_time='23:28',
                  description="""\
Created new module (tested in `lino_local.luc`).
Tried first with EventsByTicket instead of Comments,
but Comments are not usually planned.""")
    yield Session(date=i2d(20120603),
                  user=u,
                  ticket=presto_proto,
                  start_time='21:45',
                  end_time='23:28',
                  description="""\
replaced Comment by Session.
""")

    yield Session(date=i2d(20120604),
                  user=u,
                  ticket=presto_proto,
                  start_time='08:10',
                  end_time='10:30',
                  description="""\
labels, titles, tidy up, EntriesBySession.
""")

    yield Session(date=i2d(20120629),
                  user=u,
                  ticket=presto_proto,
                  start_time='00:05',
                  end_time='01:15',
                  description="""\
ProjectsByPartner
""")

    yield Session(date=i2d(20120727),
                  user=u,
                  ticket=presto_proto,
                  start_time='02:30',
                  end_time='03:15',
                  description="""\
TicketsByPartner
""")
Example #34
0
    def class_init(self):

        if self.model is not None:
            model = resolve_model(self.model, self.app_label)
            if isinstance(model, UnresolvedModel):
                # if settings.SITE.is_installed(self.app_label):
                raise Exception("Invalid model {} on table {}".format(
                    self.model, self))
            self.model = model

        if isinstance(self.model, UnresolvedModel):
            self.model = None

        if self.model is not None:
            if isinstance(self.hidden_columns, six.string_types):
                self.hidden_columns = frozenset(
                    fields.fields_list(self.model, self.hidden_columns))
            self.hidden_columns |= self.model.hidden_columns

            if isinstance(self.active_fields, six.string_types):
                self.active_fields = frozenset(
                    fields.fields_list(self.model, self.active_fields))
            self.active_fields |= self.model.active_fields
            self.hidden_elements |= self.model.hidden_elements

            # self.simple_parameters |= self.model.simple_parameters

            for b in self.model.mro():
                for k, v in list(b.__dict__.items()):
                    if isinstance(v, actions.Action):
                        existing_value = self.__dict__.get(k, NOT_PROVIDED)
                        if existing_value is NOT_PROVIDED:
                            # settings.SITE.install_help_text(
                            #     v, v.__class__)
                            setattr(self, k, v)
                        else:
                            if existing_value is None:  # 20130820
                                pass
                                # logger.info("%s disables model action '%s'",self,k)
                            else:
                                if not isinstance(existing_value,
                                                  actions.Action):
                                    raise Exception(
                                        "%s cannot install model action %s "
                                        "because name is already used "
                                        "for %r" % self, k, existing_value)

            for name in ('workflow_state_field', 'workflow_owner_field'):
                if getattr(self, name) is None:
                    setattr(self, name, getattr(self.model, name))

            for name in (  # 'disabled_fields',
                    'handle_uploaded_files',
                    # 'get_row_permission',
                    # 'disable_editing',
            ):
                if getattr(self, name) is None:
                    m = getattr(self.model, name, None)
                    if m is not None:
                        # logger.debug('20120731 Install model method %s from %r to %r',name,self.model,self)
                        setattr(self, name, model2actor(m))
                        # 'dictproxy' object does not support item assignment:
                        # self.__dict__[name] = model2actor(m)

            if self.master_key:

                master_model = None
                try:
                    fk = self.model._meta.get_field(self.master_key)
                    # x = self.model._meta.get_field_by_name(self.master_key)
                    # fk, remote, direct, m2m = x
                    # assert direct
                    # assert not m2m
                    if fk.rel is not None:
                        master_model = fk.rel.model
                    elif isinstance(fk, ChoiceListField):
                        master_model = fk.choicelist.item_class
                    elif isinstance(fk, GenericForeignKey):
                        master_model = ContentType
                    else:
                        raise Exception(
                            "Unsupported master_key {0} ({1})".format(
                                fk, fk.__class__))
                except models.FieldDoesNotExist:
                    for vf in self.model._meta.virtual_fields:
                        if vf.name == self.master_key:
                            fk = vf
                            master_model = ContentType
                            break
                if master_model is None:
                    df = getattr(self.model, self.master_key, None)
                    if df is None:
                        msg = "No field '{0}' in {1}".format(
                            self.master_key, self.model)
                        raise Exception(
                            INVALID_MK.format(self.master_key, self, msg))
                    elif isinstance(df, fields.DummyField):
                        self.abstract = True
                    else:
                        msg = "Cannot handle master key {0}".format(df)
                        msg += " (20150820 virtual fields: {0})".format([
                            vf.name for vf in self.model._meta.virtual_fields
                        ])
                        raise Exception(
                            INVALID_MK.format(self.master_key, self, msg))
                        # raise Exception(
                        #     "%s : invalid master class for master_key "
                        #     "%r in %s" % (
                        #         self, self.master_key, self.model))
                else:
                    self.master = master_model
                    self.master_field = fk
                    # self.hidden_columns |= set([fk.name])

        super(Table, self).class_init()

        if self.order_by is not None:
            if not isinstance(self.order_by, (list, tuple)):
                raise Exception("%s.order_by is %r (must be a list or tuple)" %
                                (self, self.order_by))
            if False:
                # good idea, but doesn't yet work for foreign fields,
                # e.g. order_by = ['content_type__app_label']
                for fieldname in self.order_by:
                    if fieldname.startswith('-'):
                        fieldname = fieldname[1:]
                    try:
                        fk, remote, direct, m2m = self.model._meta.get_field_by_name(
                            fieldname)
                        assert direct
                        assert not m2m
                    except models.FieldDoesNotExist:
                        raise Exception("Unknown fieldname %r in %s.order_by" %
                                        (fieldname, self))
Example #35
0
    def get_data_elem(cls, name):
        """Return the named data element. This can be a database field, a
        :class:`lino.core.fields.RemoteField`, a
        :class:`lino.core.fields.VirtualField` or a Django-style
        virtual field (GenericForeignKey).

        """
        #~ logger.info("20120202 get_data_elem %r,%r",model,name)
        if not name.startswith('__'):
            parts = name.split('__')
            if len(parts) > 1:
                # It's going to be a RemoteField
                # logger.warning("20151203 RemoteField %s in %s", name, cls)

                from lino.core import store

                model = cls
                field_chain = []
                for n in parts:
                    if model is None:
                        raise Exception(
                            "Invalid remote field {0} for {1}".format(name, cls))

                    if isinstance(model, basestring):
                        model = resolve_model(model)
                        # logger.warning("20151203 %s", model)
                        # Django 1.9 no longer resolves the
                        # rel.model of ForeignKeys on abstract
                        # models.

                    # ~ 20130508 model.get_default_table().get_handle() # make sure that all atomizers of those fields get created.
                    fld = model.get_data_elem(n)
                    if fld is None:
                        # raise Exception("Part %s of %s got None" % (n,model))
                        raise Exception(
                            "Invalid RemoteField %s.%s (no field %s in %s)" %
                            (full_model_name(model), name, n, full_model_name(model)))
                    # make sure that the atomizer gets created.
                    store.get_atomizer(model, fld, fld.name)
                    field_chain.append(fld)
                    if getattr(fld, 'rel', None):
                        if AFTER18:
                            model = fld.rel.model
                        else:
                            model = fld.rel.to
                    else:
                        model = None

                def func(obj, ar=None):
                    try:
                        for fld in field_chain:
                            if obj is None:
                                return obj
                            obj = fld._lino_atomizer.full_value_from_object(
                                obj, ar)
                        return obj
                    except Exception as e:
                        raise Exception(
                            "Error while computing %s: %s" % (name, e))
                        # ~ if False: # only for debugging
                        if True:  # see 20130802
                            logger.exception(e)
                            return str(e)
                        return None
                return fields.RemoteField(func, name, fld)

        try:
            return cls._meta.get_field(name)
        except models.FieldDoesNotExist:
            pass

        v = get_class_attr(cls, name)
        if v is not None:
            return v

        for vf in cls._meta.virtual_fields:
            if vf.name == name:
                return vf
Example #36
0
 def on_site_startup(self, site):
     from lino.core.utils import resolve_model
     self.voucher_model = resolve_model(self.voucher_model)
     self.item_model = resolve_model(self.item_model)
Example #37
0
 def on_site_startup(self, site):
     from lino.core.utils import resolve_model
     self.voucher_model = resolve_model(self.voucher_model)
     self.item_model = resolve_model(self.item_model)
Example #38
0
import logging
logger = logging.getLogger(__name__)

#~ from django.utils import unittest
#~ from django.test.client import Client
#from lino.igen import models
#from lino_xl.lib.contacts.models import Contact, Companies
#from lino_xl.lib.countries.models import Country
#~ from lino_xl.lib.contacts.models import Companies

from lino.core.utils import resolve_model
#Companies = resolve_model('contacts.Companies')
from lino.utils.djangotest import TestCase

#~ Person = resolve_model('contacts.Person')
Invoice = resolve_model('sales.Invoice')
#~ Property = resolve_model('properties.Property')
#~ PersonProperty = resolve_model('properties.PersonProperty')


class DemoTest(TestCase):
    #~ fixtures = [ 'std','demo' ]
    fixtures = 'std few_countries few_languages few_cities demo'.split()


def test01(self):
    """
    """
    self.assertEqual(Invoice.objects.all().count(), 28)
    i = Invoice.objects.all()[0]
    self.assertEqual(str(i), u"Invoice # 1")
Example #39
0
    def class_init(self):

        if self.model is not None:
            self.model = resolve_model(self.model, self.app_label)

        if isinstance(self.model, UnresolvedModel):
            self.model = None

        if self.model is not None:
            if isinstance(self.hidden_columns, basestring):
                self.hidden_columns = frozenset(
                    fields.fields_list(self.model, self.hidden_columns))
            self.hidden_columns |= self.model.hidden_columns

            if isinstance(self.active_fields, basestring):
                self.active_fields = frozenset(
                    fields.fields_list(self.model, self.active_fields))
            self.active_fields |= self.model.active_fields
            self.hidden_elements |= self.model.hidden_elements

            # self.simple_parameters |= self.model.simple_parameters

            for b in self.model.mro():
                for k, v in b.__dict__.items():
                    if isinstance(v, actions.Action):
                        existing_value = self.__dict__.get(k, NOT_PROVIDED)
                        if existing_value is NOT_PROVIDED:
                            setattr(self, k, v)
                        else:
                            if existing_value is None:  # 20130820
                                pass
                                #~ logger.info("%s disables model action '%s'",self,k)
                            else:
                                if not isinstance(
                                        existing_value, actions.Action):
                                    raise Exception(
                                        "%s cannot install model action %s "
                                        "because name is already used "
                                        "for %r" % self, k, existing_value)

            for name in ('workflow_state_field', 'workflow_owner_field'):
                if getattr(self, name) is None:
                    setattr(self, name, getattr(self.model, name))

            for name in (  # 'disabled_fields',
                'handle_uploaded_files',
                #~ 'get_row_permission',
                #~ 'disable_editing',
            ):
                if getattr(self, name) is None:
                    m = getattr(self.model, name, None)
                    if m is not None:
                        #~ logger.debug('20120731 Install model method %s from %r to %r',name,self.model,self)
                        setattr(self, name, model2actor(m))
                        #~ 'dictproxy' object does not support item assignment:
                        #~ self.__dict__[name] = model2actor(m)

            if self.master_key:

                master_model = None
                try:
                    fk = self.model._meta.get_field(self.master_key)
                    # x = self.model._meta.get_field_by_name(self.master_key)
                    # fk, remote, direct, m2m = x
                    # assert direct
                    # assert not m2m
                    if fk.rel is not None:
                        master_model = fk.rel.model
                    elif isinstance(fk, ChoiceListField):
                        master_model = fk.choicelist.item_class
                    elif isinstance(fk, GenericForeignKey):
                        master_model = ContentType
                    else:
                        raise Exception("Oops: {0}".format(fk))
                except models.FieldDoesNotExist:
                    for vf in self.model._meta.virtual_fields:
                        if vf.name == self.master_key:
                            fk = vf
                            master_model = ContentType
                            break
                if master_model is None:
                    df = getattr(self.model, self.master_key, None)
                    if df is None:
                        msg = "No field '{0}' in {1}".format(
                            self.master_key, self.model)
                        raise Exception(INVALID_MK.format(
                            self.master_key, self, msg))
                    elif isinstance(df, fields.DummyField):
                        self.abstract = True
                    else:
                        msg = "Cannot handle master key {0}".format(df)
                        msg += " (20150820 virtual fields: {0})".format(
                            [vf.name for vf in
                             self.model._meta.virtual_fields])
                        raise Exception(INVALID_MK.format(
                            self.master_key, self, msg))
                        # raise Exception(
                        #     "%s : invalid master class for master_key "
                        #     "%r in %s" % (
                        #         self, self.master_key, self.model))
                else:
                    self.master = master_model
                    self.master_field = fk
                    # self.hidden_columns |= set([fk.name])

        super(Table, self).class_init()

        if self.order_by is not None:
            if not isinstance(self.order_by, (list, tuple)):
                raise Exception("%s.order_by is %r (must be a list or tuple)" %
                                (self, self.order_by))
            if False:
                # good idea, but doesn't yet work for foreign fields,
                # e.g. order_by = ['content_type__app_label']
                for fieldname in self.order_by:
                    if fieldname.startswith('-'):
                        fieldname = fieldname[1:]
                    try:
                        fk, remote, direct, m2m = self.model._meta.get_field_by_name(
                            fieldname)
                        assert direct
                        assert not m2m
                    except models.FieldDoesNotExist:
                        raise Exception("Unknown fieldname %r in %s.order_by" %
                                        (fieldname, self))
Example #40
0
File: std.py Project: TonisPiip/xl
def objects():

    #~ yield companyType('Firma','Firma')
    #~ yield companyType('asbl','asbl')
    #~ yield companyType('A.S.B.L.','A.S.B.L.')
    #~ yield companyType('sprl','sprl')
    #~ yield companyType('GmbH','GmbH')
    #~ yield companyType('AG','AG')
    #~ yield companyType('S.A.','S.A.')
    #~ yield companyType('S.C.','S.C.')
    #~ yield companyType('V.o.G.','V.o.G.')
    #~ yield companyType('G.o.E.','G.o.E.')
    #~ yield companyType('A.S.B.L.','Association sans but lucratif')
    #~ yield companyType('Maison','Maison')
    #~ yield companyType('Fachklinik','Fachklinik')
    #~ yield companyType("Centre d'Accueil d'Urgence","Centre d'Accueil d'Urgence")

    #~ yield companyType(**babel_values('name',
    #~ en=u"Public Limited Company",
    #~ nl=u'NV (Naamloze Vennootschap)',
    #~ fr=u'SA (Société Anonyme)',
    #~ de=u"AG (Aktiengesellschaft)"))

    for ct in COMPANY_TYPES:
        yield companyType(**ct)

    yield roletype(**babel_values('name',
                                  en="Manager",
                                  fr='Gérant',
                                  de="Geschäftsführer",
                                  et="Tegevjuht"))
    yield roletype(**babel_values(
        'name', en="Director", fr='Directeur', de="Direktor", et="Direktor"))
    yield roletype(**babel_values(
        'name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär"))
    yield roletype(**babel_values('name',
                                  en="IT Manager",
                                  fr='Gérant informatique',
                                  de="EDV-Manager",
                                  et="IT manager"))
    yield roletype(**babel_values(
        'name', en="President", fr='Président', de="Präsident",
        et="President"))

    if settings.SITE.is_installed('contenttypes'):

        from django.contrib.contenttypes.models import ContentType

        I = Instantiator('gfks.HelpText', 'content_type field help_text').build

        Person = resolve_model("contacts.Person")
        t = ContentType.objects.get_for_model(Person)

        #~ yield I(t,'birth_date',u"""\
        #~ Unkomplette Geburtsdaten sind erlaubt, z.B.
        #~ <ul>
        #~ <li>00.00.1980 : irgendwann in 1980</li>
        #~ <li>00.07.1980 : im Juli 1980</li>
        #~ <li>23.07.0000 : Geburtstag am 23. Juli, Alter unbekannt</li>
        #~ </ul>
        #~ """)

        Partner = resolve_model('contacts.Partner')
        t = ContentType.objects.get_for_model(Partner)
        yield I(
            t, 'language', u"""\
    Die Sprache, in der Dokumente ausgestellt werden sollen.
    """)
Example #41
0
    def get_data_elem(cls, name):
        """Return the named data element. This can be a database field, a
        :class:`lino.core.fields.RemoteField`, a
        :class:`lino.core.fields.VirtualField` or a Django-style
        virtual field (GenericForeignKey).

        """
        #~ logger.info("20120202 get_data_elem %r,%r",model,name)
        if not name.startswith('__'):
            parts = name.split('__')
            if len(parts) > 1:
                # It's going to be a RemoteField
                # logger.warning("20151203 RemoteField %s in %s", name, cls)

                from lino.core import store

                model = cls
                field_chain = []
                for n in parts:
                    if model is None:
                        raise Exception(
                            "Invalid remote field {0} for {1}".format(name, cls))

                    if isinstance(model, six.string_types):
                        model = resolve_model(model)
                        # logger.warning("20151203 %s", model)
                        # Django 1.9 no longer resolves the
                        # rel.model of ForeignKeys on abstract
                        # models.

                    # ~ 20130508 model.get_default_table().get_handle() # make sure that all atomizers of those fields get created.
                    fld = model.get_data_elem(n)
                    if fld is None:
                        # raise Exception("Part %s of %s got None" % (n,model))
                        raise Exception(
                            "Invalid RemoteField %s.%s (no field %s in %s)" %
                            (full_model_name(model), name, n, full_model_name(model)))
                    # make sure that the atomizer gets created.
                    store.get_atomizer(model, fld, fld.name)
                    field_chain.append(fld)
                    if getattr(fld, 'rel', None):
                        if AFTER18:
                            model = fld.rel.model
                        else:
                            model = fld.rel.to
                    else:
                        model = None

                def func(obj, ar=None):
                    try:
                        for fld in field_chain:
                            if obj is None:
                                return obj
                            obj = fld._lino_atomizer.full_value_from_object(
                                obj, ar)
                        return obj
                    except Exception as e:
                        raise Exception(
                            "Error while computing %s: %s" % (name, e))
                        # ~ if False: # only for debugging
                        if True:  # see 20130802
                            logger.exception(e)
                            return str(e)
                        return None
                return fields.RemoteField(func, name, fld)

        try:
            return cls._meta.get_field(name)
        except models.FieldDoesNotExist:
            pass

        v = get_class_attr(cls, name)
        if v is not None:
            return v

        for vf in cls._meta.virtual_fields:
            if vf.name == name:
                return vf
Example #42
0
 def attach_to_model(self, model, name):
     self.child_model = resolve_model(
         self.child_model, model._meta.app_label)
     VirtualField.attach_to_model(self, model, name)
Example #43
0
from lino_xl.lib.contacts.utils import name2kw, street2kw
from lino.utils import join_words
#~ from lino_xl.lib.contacts.models import name2kw, street2kw, join_words
from lino.utils.instantiator import Instantiator

from lino.core.utils import resolve_model, obj2str
from lino.core.utils import is_valid_email
import lino

from lino.utils import confirm, iif
from lino.core.utils import app_labels
from lino_xl.lib.beid.mixins import BeIdCardTypes


Activity = resolve_model('pcsw.Activity')
Country = resolve_model('countries.Country')
Place = resolve_model('countries.Place')
Person = resolve_model('contacts.Person')
Company = resolve_model('contacts.Company')


def store(kw, **d):
    for k, v in d.items():
        if v is not None:
        # see :doc:`/blog/2011/0711`
        #~ if v:
            kw[k] = v

#~ def convert_username(name):
    #~ return name.lower()
Example #44
0
#~ print 20120225, 'settings.FIXTURE_DIRS is', settings.FIXTURE_DIRS

dblogger.info("Imported contacts demo fixture")

COUNT = 0

#~ addresstype= Instantiator('contacts.AddressType',"name").build
role = Instantiator('contacts.Role', "name").build
#~ person = Instantiator('contacts.Person',"first_name last_name").build
#~ company = Instantiator('contacts.Company',"name").build
#~ contact = Instantiator('contacts.Contact').build

Company = contacts.Company
Person = contacts.Person
User = contacts.User
City = resolve_model('countries.City')

if not settings.SITE.abstract_address:
    Address = contacts.Address
    address = Instantiator(Address,
                           "country zip_code city:name street street_no").build


def company(name, country_id, zip_code, city, street, street_no):
    if settings.SITE.abstract_address:
        city = City.objects.get(name=city)
        yield Company(name=name,
                      country_id=country_id,
                      zip_code=zip_code,
                      city=city,
                      street=street,
Example #45
0
 def attach_to_model(self, model, name):
     self.child_model = resolve_model(
         self.child_model, model._meta.app_label)
     VirtualField.attach_to_model(self, model, name)
Example #46
0
def objects():

    ClientContactType = rt.modules.pcsw.ClientContactType

    Person = resolve_model('contacts.Person')
    Company = resolve_model('contacts.Company')
    #~ Contact = resolve_model('contacts.Contact')
    Role = resolve_model('contacts.Role')
    RoleType = resolve_model('contacts.RoleType')
    Authority = resolve_model('users.Authority')
    #~ Country = resolve_model('countries.Country')
    Client = resolve_model('pcsw.Client')

    person = Instantiator(Person).build
    client = Instantiator(Client).build
    company = Instantiator(Company).build
    #~ contact = Instantiator(Contact).build
    role = Instantiator(Role).build
    #~ link = Instantiator(Link).build
    #~ exam_policy = Instantiator('isip.ExamPolicy').build

    Place = resolve_model('countries.Place')
    #~ Job = resolve_model('jobs.Job')
    #~ Place = settings.SITE.modules.countries.Place
    StudyType = resolve_model('cv.StudyType')
    #~ Country = resolve_model('countries.Country')
    Property = resolve_model('properties.Property')

    eupen = Place.objects.get(name__exact='Eupen')
    #~ stvith = Place.objects.get(zip_code__exact='4780')
    stvith = Place.objects.get(name__in=('Sankt Vith', 'Saint-Vith'))
    kettenis = Place.objects.get(name__exact='Kettenis')
    vigala = Place.objects.get(name__exact='Vigala')
    ee = countries.Country.objects.get(pk='EE')
    be = belgium = countries.Country.objects.get(isocode__exact='BE')
    andreas = Person.objects.get(name__exact="Arens Andreas")
    annette = Person.objects.get(name__exact="Arens Annette")
    hans = Person.objects.get(name__exact="Altenberg Hans")
    ulrike = Person.objects.get(name__exact="Charlier Ulrike")
    erna = Person.objects.get(name__exact=u"Ärgerlich Erna")

    ## Coaching types
    # We use only abbreviated names in `CoachingType.name` because the
    # users usually know these abbrevs.

    kw = dd.str2kw('name', _("Colleague"))
    COLLEAGUE = cal.GuestRole(**kw)
    yield COLLEAGUE

    # id must match `isip.ContactBase.person_changed`
    ASD = pcsw.CoachingType(
        id=isip.COACHINGTYPE_ASD,
        does_integ=False,
        does_gss=True,
        eval_guestrole=COLLEAGUE,
        **dd.babelkw(
            'name',
            de="ASD",  # (Allgemeiner Sozialdienst)
            nl="ASD",  # (Algemene Sociale Dienst)
            fr="SSG",  # (Service social général)
            en="General",  # (General Social Service)
        ))
    yield ASD

    DSBE = pcsw.CoachingType(
        id=isip.COACHINGTYPE_DSBE,
        does_gss=False,
        does_integ=True,
        eval_guestrole=COLLEAGUE,
        **dd.babelkw(
            'name',
            de="DSBE",  # (Dienst für Sozial-Berufliche Eingliederung)
            fr="SI",  # Service intégration
            en="Integ",  # Integration service
        ))
    yield DSBE

    DEBTS = pcsw.CoachingType(
        does_gss=False,
        does_integ=False,
        **dd.babelkw(
            'name',
            de="Schuldnerberatung",
            fr="Médiation de dettes",
            en="Debts mediation",
        ))
    yield DEBTS

    melanie = person(first_name="Mélanie", last_name="Mélard",
                     email=settings.SITE.demo_email,
                     city=eupen, country='BE', gender=dd.Genders.female,
                     language='fr')

    ## newcomers : Melanie does not work with newcomers because she is
    ## the boss. Hubert does live consultations (no appointments). And
    ## Alicia does only appointments but no life
    ## consultations. Caroline and Judith do both.
    yield melanie
    melanie = users.User(
        username="******", partner=melanie, profile='110',
        coaching_type=DSBE,
        newcomer_consultations=False, newcomer_appointments=False)
    yield melanie

    hubert = person(first_name=u"Hubert", last_name=u"Huppertz",
                    email=settings.SITE.demo_email,
                    city=kettenis, country='BE', gender=dd.Genders.male)
    yield hubert
    hubert = users.User(
        username="******", partner=hubert, profile='100',
        coaching_type=DSBE,
        newcomer_consultations=True, newcomer_appointments=False)
    yield hubert

    alicia = person(
        first_name=u"Alicia", last_name=u"Allmanns",
        email=settings.SITE.demo_email,
        city=kettenis, country='BE',
        # gender=dd.Genders.female,  # don't set gender
        language='fr')
    yield alicia
    alicia = users.User(
        username="******", partner=alicia, profile='100',
        coaching_type=DSBE,
        newcomer_consultations=True, newcomer_appointments=True)
    yield alicia

    theresia = person(first_name="Theresia", last_name="Thelen",
                      email=settings.SITE.demo_email,
                      city=eupen, country='BE', gender=dd.Genders.female)
    yield theresia
    theresia = users.User(username="******", partner=theresia, profile='210')
    yield theresia

    nicolas = users.User(username="******", profile='')
    yield nicolas

    # yield Authority(user=alicia, authorized=hubert)
    # yield Authority(user=alicia, authorized=melanie)
    # yield Authority(user=hubert, authorized=melanie)
    yield Authority(user=hubert, authorized=theresia)
    yield Authority(user=alicia, authorized=theresia)
    yield Authority(user=melanie, authorized=theresia)

    caroline = users.User(
        username="******", first_name="Caroline", last_name="Carnol",
        profile='200',
        coaching_type=ASD,
        newcomer_consultations=True, newcomer_appointments=True)
    yield caroline

    obj = person(first_name="Judith", last_name="Jousten",
                 email=settings.SITE.demo_email,
                 city=eupen, country='BE', gender=dd.Genders.female)
    yield obj

    judith = users.User(
        username="******", partner=obj, profile='400',
        coaching_type=ASD,
        newcomer_consultations=True, newcomer_appointments=True)
    yield judith

    yield users.User(
        username="******", first_name="Patrick",
        last_name="Paraneau", profile='910',
        email=settings.SITE.demo_email)

    # for obj in pcsw.CoachingType.objects.all():
    #     yield users.Team(**dd.babelkw('name', **field2kw(obj, 'name')))

    obj = cal.GuestRole(
        # email_template="Visitor.eml.html",
        **dd.babelkw(
            'name',
            de="Besucher",
            fr="Visiteur",
            en="Visitor",
            et="Külaline",
        ))
    yield obj
    settings.SITE.site_config.update(client_guestrole=obj)

    yield cal.GuestRole(**dd.babelkw('name',
                                     de=u"Vorsitzender",
                                     fr=u"Président",
                                     en=u"Chairman",
                                     et=u"Eesistuja",
                                 ))
    yield cal.GuestRole(**dd.babelkw('name',
                                     de=u"Schriftführer",
                                     fr=u"Greffier",
                                     en=u"Reporter",
                                     et=u"Sekretär",
                                 ))

    calendar = Instantiator('cal.EventType').build

    kw = dict(invite_client=False, is_appointment=False)
    kw.update(dd.str2kw('name', _("Consultations with client")))
    kw.update(dd.str2kw('event_label', _("Consultation")))
    # kw.update(dd.babelkw(
    #     'name',
    #     de="Visiten (ohne Verabredung)",
    #     fr="Consultations sans rendez-vous",
    #     en="Prompt consultation",
    #     et="Külaline",
    # ))
    obj = calendar(**kw)
    yield obj
    settings.SITE.site_config.update(prompt_calendar=obj)

    kw = dict(invite_client=True)
    kw.update(dd.str2kw("name", _("External meetings with client")))
    kw.update(dd.str2kw("event_label", _("External meeting")))
    yield calendar(**kw)

    kw = dict(invite_client=True)
    kw.update(dd.str2kw("name", _("Informational meetings")))
    kw.update(dd.str2kw("event_label", _("Informational meeting")))
    yield calendar(**kw)

    kw = dict(invite_client=False)
    kw.update(dd.str2kw("name", _("Internal meetings")))
    kw.update(dd.str2kw("event_label", _("Internal meeting")))
    yield calendar(**kw)
    # yield calendar(**dd.babelkw('name',
    #                             de=u"Versammlung intern",
    #                             fr=u"Réunions internes",
    #                             en=u"Internal meetings"))

    kw = dict(invite_client=False)
    kw.update(dd.str2kw("name", _("External meetings")))
    kw.update(dd.str2kw("event_label", _("External meeting")))
    yield calendar(**kw)
    # yield calendar(**dd.babelkw('name',
    #                             de=u"Versammlung extern",
    #                             fr=u"Réunions externes",
    #                             en=u"External meetings"))

    kw = dict(invite_client=False)
    kw.update(dd.str2kw("name", _("Private")))
    yield calendar(**kw)
    # yield calendar(**dd.babelkw('name',
    #                             de="Privat",
    #                             fr="Privé",
    #                             en="Private"))

    sector = Instantiator(cv.Sector).build
    for ln in SECTORS_LIST.splitlines():
        if ln:
            a = ln.split('|')
            if len(a) == 3:
                kw = dict(en=a[0], fr=a[1], de=a[2])
                yield sector(**dd.babelkw('name', **kw))

    horeca = cv.Sector.objects.get(pk=5)
    function = Instantiator(cv.Function, sector=horeca).build
    yield function(**dd.babelkw('name',
                             de=u"Kellner",
                             fr=u'Serveur',
                             en=u'Waiter',
                             ))
    yield function(**dd.babelkw('name',
                             de=u"Koch",
                             fr=u'Cuisinier',
                             en=u'Cook',
                             ))
    yield function(**dd.babelkw('name',
                             de=u"Küchenassistent",
                             fr=u'Aide Cuisinier',
                             en=u'Cook assistant',
                             ))
    yield function(**dd.babelkw('name',
                             de=u"Tellerwäscher",
                             fr=u'Plongeur',
                             en=u'Dishwasher',
                             ))

    contractType = Instantiator(jobs.ContractType, "ref",
                                exam_policy=3).build
    yield contractType('art60-7a',
                       **dd.babelkw('name',
                                 de=u"Sozialökonomie",
                                 fr=u'économie sociale',
                                 en=u'social economy',
                                 ))
    yield contractType('art60-7b',
                       **dd.babelkw('name',
                                 de=u"Sozialökonomie - majoré",
                                 fr=u'économie sociale - majoré',
                                 en=u'social economy - increased',
                                 ))
    yield contractType('art60-7c',
                       **dd.babelkw('name',
                                 de=u"mit Rückerstattung",
                                 fr=u'avec remboursement',
                                 en=u'social economy with refund',
                                 ))
    yield contractType('art60-7d',
                       **dd.babelkw('name',
                                 de=u"mit Rückerstattung Schule",
                                 fr=u'avec remboursement école',
                                 en=u'social economy school',
                                 ))
    yield contractType('art60-7e',
                       **dd.babelkw('name',
                                 de=u"Stadt Eupen",
                                 fr=u"ville d'Eupen",
                                 en=u'town',
                                 ))

    contractType = Instantiator(isip.ContractType, "ref",
                                exam_policy=1).build
    yield contractType("vsea", needs_study_type=True, **dd.babelkw(
        'name',
        de=u"VSE Ausbildung",
        fr=u"VSE Ausbildung",
        en=u"VSE Ausbildung",
    ))
    yield contractType("vseb", **dd.babelkw('name',
                                         de=u"VSE Arbeitssuche",
                                         fr=u"VSE Arbeitssuche",
                                         en=u"VSE Arbeitssuche",
                                         ))
    yield contractType("vsec", **dd.babelkw('name',
                                         de=u"VSE Lehre",
                                         fr=u"VSE Lehre",
                                         en=u"VSE Lehre",
                                         ))
    yield contractType("vsed",
                       needs_study_type=True,
                       **dd.babelkw('name',
                                 de=u"VSE Vollzeitstudium",
                                 fr=u"VSE Vollzeitstudium",
                                 en=u"VSE Vollzeitstudium",
                             ))
    yield contractType("vsee", **dd.babelkw('name',
                                         de=u"VSE Sprachkurs",
                                         fr=u"VSE Sprachkurs",
                                         en=u"VSE Sprachkurs",
                                         ))

    t = RoleType.objects.get(pk=4)  # It manager
    t.use_in_contracts = False
    t.save()

    #~ country = Instantiator('countries.Country',"isocode name").build
    #~ yield country('SUHH',"Soviet Union")
    #~ cpas = company(name=u"ÖSHZ Eupen",city=eupen,country=belgium)
    cpas = company(name=u"ÖSHZ Kettenis", city=kettenis, country=belgium)
    yield cpas
    bisa = company(name=u"BISA", city=eupen, country=belgium)
    yield bisa
    bisa_dir = role(company=bisa, person=annette, type=1)
    yield bisa_dir
    rcycle = company(name=u"R-Cycle Sperrgutsortierzentrum",
                     city=eupen, country=belgium)
    yield rcycle
    rcycle_dir = role(company=rcycle, person=andreas, type=1)
    yield rcycle_dir
    yield role(company=rcycle, person=erna, type=2)
    # IT manager : no contracts
    yield role(company=rcycle, person=ulrike, type=4)
    yield company(name=u"Die neue Alternative V.o.G.", city=eupen, country=belgium)
    proaktiv = company(name=u"Pro Aktiv V.o.G.", city=eupen, country=belgium)
    yield proaktiv
    proaktiv_dir = role(company=proaktiv, person=hans, type=1)
    # IT manager : no contracts
    yield role(company=proaktiv, person=ulrike, type=4)
    yield proaktiv_dir
    yield company(name=u"Werkstatt Cardijn V.o.G.", city=eupen, country=belgium)
    yield company(name=u"Behindertenstätten Eupen", city=eupen, country=belgium)
    yield company(name=u"Beschützende Werkstätte Eupen", city=eupen, country=belgium)

    kw = dd.str2kw('name', _("Health insurance"))
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium)
    #~ kw = dict(is_health_insurance=True,country=belgium)
    yield company(name="Alliance Nationale des Mutualités Chrétiennes", **kw)
    yield company(name="Mutualité Chrétienne de Verviers - Eupen", **kw)
    yield company(name="Union Nationale des Mutualités Neutres", **kw)
    yield company(name="Mutualia - Mutualité Neutre", **kw)
    yield company(name="Solidaris - Mutualité socialiste et syndicale de la province de Liège", **kw)

    fkw = dd.str2kw('name', _("Pharmacy"))  # Apotheke
    cct = rt.modules.pcsw.ClientContactType.objects.get(**fkw)
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield company(
        name="Apotheke Reul",
        street='Klosterstraße', street_no=20, **kw)
    yield company(
        name="Apotheke Schunck", street='Bergstraße', street_no=59, **kw)
    yield company(
        name="Pharmacies Populaires de Verviers",
        street='Aachener Straße', street_no=258, **kw)
    yield company(
        name="Bosten-Bocken A", street='Haasstraße', street_no=6, **kw)

    kw = dd.str2kw('name', _("Advocate"))
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield company(name=u"Brüll Christine", street=u'Schilsweg', street_no=4, **kw)
    yield company(name=u"Brocal Catherine", street=u'Neustraße', street_no=115, **kw)
    yield company(name=u"Bourseaux Alexandre", street=u'Aachener Straße', street_no=21, **kw)
    yield company(name=u"Baguette Stéphanie", street=u'Gospertstraße', street_no=24, **kw)

    # Bailiff = Gerichtsvollzieher = Huissier de justice
    kw = dd.str2kw('name', _("Bailiff"))
    if dd.is_installed('debts'):
        kw.update(is_bailiff=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield company(name="Demarteau Bernadette",
                  street='Aachener Straße', street_no=25, **kw)
    kw.update(city=stvith)
    yield company(name="Schmitz Marc", street='Rodter Straße',
                  street_no=43, street_box="B", **kw)

    # Inkasso-Unternehmen
    kw = dd.str2kw('name', _("Debt collecting company"))
    if dd.is_installed('debts'):
        kw.update(is_bailiff=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield company(name="Cashback sprl",
                  street='Vervierser Straße', street_no=1, **kw)
    yield company(name="Money Wizard AS",
                  street='Neustraße', street_no=1, **kw)

    # settings.SITE.site_config.debts_bailiff_type = cct
    # yield settings.SITE.site_config

    def person2client(p, **kw):
        c = mti.insert_child(p, Client)
        for k, v in kw.items():
            setattr(c, k, v)
        c.client_state = pcsw.ClientStates.coached
        c.save()
        return Client.objects.get(pk=p.pk)

    #~ luc = Person.objects.get(name__exact="Saffre Luc")
    #~ luc = person2client(luc,national_id = '680601 053-29')
    #~ luc.birth_place = 'Eupen'
    #~ luc.birth_date = '1968-06-01'
    #~ luc.birth_country = be
    #~ luc.full_clean()
    #~ luc.save()
    #~
    #~ ly = person(first_name="Ly",last_name="Rumma",
      #~ city=vigala,country='EE',
      #~ gender=dd.Genders.female)
    #~ yield ly
    #~ mari = person(first_name="Mari",last_name="Saffre",
      #~ city=vigala,country='EE',
      #~ gender=dd.Genders.female)
    #~ yield mari
    #~ iiris = person(first_name="Iiris",last_name="Saffre",
      #~ city=vigala,country='EE',
      #~ gender=dd.Genders.female)
    #~ yield iiris

    gerd = person(first_name="Gerd",
                  last_name="Gerkens", city=kettenis,
                  email=settings.SITE.demo_email,  # '*****@*****.**'
                  country='BE', gender=dd.Genders.male)
    yield gerd
    yield role(company=cpas, person=gerd, type=4)

    # see :blogentry:`20111007`
    tatjana = client(
        first_name=u"Tatjana", last_name=u"Kasennova",
        #~ first_name=u"Татьяна",last_name=u"Казеннова",
        city=kettenis, country='BE',
        #~ national_id='1237',
        birth_place="Moskau",  # birth_country='SUHH',
        client_state=pcsw.ClientStates.newcomer,
        #~ newcomer=True,
        gender=dd.Genders.female)
    yield tatjana

    michael = Person.objects.get(name__exact="Mießen Michael")
    jean = Person.objects.get(name__exact="Radermacher Jean")
    #~ yield cpas
    sc = settings.SITE.site_config
    sc.site_company = cpas
    sc.signer1 = michael
    sc.signer2 = jean
    yield sc
    yield role(company=cpas,
               person=michael,
               type=sc.signer1_function)
    yield role(company=cpas,
               person=jean,
               type=sc.signer2_function)

    bernard = Person.objects.get(name__exact="Bodard Bernard")

    kw = dd.str2kw('name', _("Employment office"))  # Arbeitsvermittler
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    adg = company(name=u"Arbeitsamt der D.G.", **kw)
    adg.save()
    yield adg
    settings.SITE.site_config.job_office = adg
    yield settings.SITE.site_config
    adg_dir = role(company=adg, person=bernard, type=1)
    yield adg_dir

    kw = dd.str2kw('name', _("Physician"))  # Arzt
    if dd.is_installed('aids'):
        kw.update(can_refund=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield person(first_name="Waltraud", last_name="Waldmann", **kw)

    kw = dd.str2kw('name', _("Family doctor"))  # Hausarzt
    if dd.is_installed('aids'):
        kw.update(can_refund=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    yield person(first_name="Werner", last_name="Wehnicht", **kw)

    kw = dd.str2kw('name', _("Dentist"))
    if dd.is_installed('aids'):
        kw.update(can_refund=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium,
              city=eupen, title="Dr.")
    yield person(first_name="Carmen", last_name="Castou", **kw)
    yield person(first_name="Walter", last_name="Waldmann", **kw)

    kw = dd.str2kw('name', _("Pediatrician"))
    if dd.is_installed('aids'):
        kw.update(can_refund=True)
    cct = ClientContactType(**kw)
    yield cct
    kw = dict(client_contact_type=cct, country=belgium,
              city=eupen, title="Dr.")
    yield person(first_name="Killian", last_name="Kimmel", **kw)

    # kw = dd.str2kw('name', _("Landlord"))  # Vermieter
    # if dd.is_installed('aids'):
    #     kw.update(can_refund=True)
    # cct = ClientContactType(**kw)
    # yield cct
    # kw = dict(client_contact_type=cct, country=belgium, city=eupen)
    # yield person(first_name="Vera", last_name="Veltz", **kw)
    # yield person(first_name="Vanessa", last_name="Veithen", **kw)

    #~ from django.core.exceptions import ValidationError
    # ~ # a circular reference: bernard is contact for company adg and also has himself as `job_office_contact`
    #~ try:
      #~ bernard.job_office_contact = adg_dir
      #~ bernard.clean()
      #~ bernard.save()
    #~ except ValidationError:
        #~ pass
    #~ else:
        #~ raise Exception("Expected ValidationError")

    DIRECTORS = (annette, hans, andreas, bernard)

    #~ USERS = Cycler(root,melanie,hubert,alicia)
    AGENTS = Cycler(melanie, hubert, alicia, judith)
    COACHINGTYPES = Cycler(pcsw.CoachingType.objects.filter(
        does_gss=False, does_integ=False))

    #~ CLIENTS = Cycler(andreas,annette,hans,ulrike,erna,tatjana)
    count = 0
    #~ for person in Person.objects.filter(gender__isnull=False):
    for person in Person.objects.exclude(gender=''):
        if not person.birth_date:  # not those from humanlinks
            if users.User.objects.filter(partner=person).count() == 0:
                if contacts.Role.objects.filter(person=person).count() == 0:
                    birth_date = settings.SITE.demo_date(-170 * count - 16 * 365)
                    national_id = generate_ssin(birth_date, person.gender)

                    client = person2client(person,
                                           national_id=national_id,
                                           birth_date=birth_date)
                    # youngest client is 16; 170 days between each client

                    count += 1
                    if count % 2:
                        client.client_state = pcsw.ClientStates.coached
                    elif count % 5:
                        client.client_state = pcsw.ClientStates.newcomer
                    else:
                        client.client_state = pcsw.ClientStates.former

                    # Dorothée is three times in our database
                    if client.first_name == "Dorothée":
                        client.national_id = None
                        client.birth_date = ''

                    client.full_clean()
                    client.save()

    #~ CLIENTS = Cycler(Client.objects.filter(is_active=True,newcomer=False))
    CLIENTS = Cycler(
        Client.objects.filter(client_state=pcsw.ClientStates.coached))

    #~ oshz = Company.objects.get(name=u"ÖSHZ Eupen")

    #~ project = Instantiator('projects.Project').build
    #~ note = Instantiator('notes.Note').build
    langk = Instantiator('cv.LanguageKnowledge').build

    #~ prj = project(name="Testprojekt",company=oshz)
    #~ yield prj
    #~ yield note(user=user,project=prj,date=i2d(20091006),subject="Programmierung",company=oshz)

    #~ prj = project(name="Testprojekt",company=oshz)
    #~ yield prj
    #~ yield note(user=user,project=prj,date=i2d(20091007),subject="Anschauen",company=oshz)

    Note = resolve_model('notes.Note')
    USERS = Cycler(users.User.objects.all())
    SUBJECTS = Cycler(u"""
    Erstgespräch
    Versammlung beim AG
    Zwischenbericht
    Krisensitzung
    """.splitlines())

    for i in range(10):
        yield Note(user=USERS.pop(),
                   date=settings.SITE.demo_date(days=i),
                   subject=SUBJECTS.pop())

    schule = StudyType.objects.get(pk=1)
    # uni = StudyType.objects.get(pk=4)
    abi = u"Abitur"
    study = Instantiator('cv.Study').build

    gerd = CLIENTS.pop()
    luc = CLIENTS.pop()
    ly = CLIENTS.pop()
    mari = CLIENTS.pop()
    iiris = CLIENTS.pop()

    luc.card_number = '591413288107'
    luc.card_valid_from = i2d(20110819)
    luc.card_valid_until = i2d(20160819)
    luc.card_issuer = "Eupen"
    luc.card_type = BeIdCardTypes.belgian_citizen
    luc.save()
    luc.make_demo_picture()

    gerd.card_number = '123456789012'
    gerd.card_valid_from = i2d(20120819)
    gerd.card_valid_until = i2d(20130818)
    gerd.card_issuer = "Eupen"
    gerd.card_type = BeIdCardTypes.foreigner_c
    gerd.save()
    gerd.make_demo_picture()

    yield study(person=luc, type=schule, content=abi,
                start_date='19740901', end_date='19860630')
    yield study(person=gerd, type=schule, content=abi,
                start_date='19740901', end_date='19860630')

    yield langk(person=luc, language='ger', written='4', spoken='4')
    yield langk(person=gerd, language='ger', written='4', spoken='4')
    yield langk(person=mari, language='ger', written='2', spoken='4')
    yield langk(person=iiris, language='ger', written='0', spoken='4')
    yield langk(person=ly, language='ger', written='2', spoken='1')

    yield langk(person=luc, language='fre', written='4', spoken='3')
    yield langk(person=gerd, language='fre', written='4', spoken='3')

    yield langk(person=luc, language='eng', written='4', spoken='3')
    yield langk(person=gerd, language='eng', written='4', spoken='3')
    yield langk(person=ly, language='eng', written='3', spoken='3')

    yield langk(person=gerd, language='dut', written='3', spoken='3')

    yield langk(person=luc, language='est', written='3', spoken='3')
    yield langk(person=ly, language='est', written='4', spoken='4')
    yield langk(person=mari, language='est', written='3', spoken='4')
    yield langk(person=iiris, language='est', written='0', spoken='3')

    jobtype = Instantiator(jobs.JobType, 'name').build
    art607 = jobtype(u'Sozialwirtschaft = "majorés"')
    yield art607
    yield jobtype(u'Intern')
    yield jobtype(u'Extern (Öffentl. VoE mit Kostenrückerstattung)')
    yield jobtype(u'Extern (Privat Kostenrückerstattung)')
    #~ yield jobtype(u'VSE')
    yield jobtype(u'Sonstige')

    rcycle = mti.insert_child(rcycle, jobs.JobProvider)
    yield rcycle
    bisa = mti.insert_child(bisa, jobs.JobProvider)
    yield bisa
    proaktiv = mti.insert_child(proaktiv, jobs.JobProvider)
    yield proaktiv

    # jobs (Art.60-7)
    CSTATES = Cycler(jobs.CandidatureStates.objects())
    JOBS_CONTRACT_TYPES = Cycler(jobs.ContractType.objects.all())
    JTYPES = Cycler(jobs.JobType.objects.all())

    PROVIDERS = Cycler(jobs.JobProvider.objects.all())
    SECTORS = Cycler(cv.Sector.objects.all())
    FUNCTIONS = Cycler(cv.Function.objects.all())
    REMARKS = Cycler(
        _("A very hard job."),
        '',
        _("No supervisor. Only for independent people."), '', '', '')

    for i in range(8):
        f = FUNCTIONS.pop()
        yield jobs.Job(provider=PROVIDERS.pop(),
                       type=JTYPES.pop(),
                       contract_type=JOBS_CONTRACT_TYPES.pop(),
                       name=unicode(f),
                       remark=REMARKS.pop(),
                       sector=SECTORS.pop(), function=f)

    JOBS = Cycler(jobs.Job.objects.all())

    for i in range(40):
        yield jobs.Candidature(job=JOBS.pop(),
                               person=CLIENTS.pop(),
                               state=CSTATES.pop(),
                               date_submitted=settings.SITE.demo_date(-40 + i))

    # reset SECTORS and FUNCTIONS
    SECTORS = Cycler(cv.Sector.objects.all())
    FUNCTIONS = Cycler(cv.Function.objects.all())

    obj = jobs.Offer(
        name="Übersetzer DE-FR (m/w)",
        remark="""\
Wir sind auf der Suche nach einem Deutsch-Französich Übersetzer 
(M/F) um einen Selbständigenr zu Geschäftsessen und kommerziellen 
Termine zu begleiten. Sie übernehmen die Übersetzung von Gespräche 
während kommerziellen Kontakte mit deutschen Kunden.
Es ist spontane und pünktliche Aufträge, den ganzen Tag, in
Eupen und/oder Deutschland.
Regelmäßigkeit: 1-2 Mal pro Monat, je nach Bedarf.
Flexibilität: die Termine sind je nach Kandidat anpassbar.""",
        provider=PROVIDERS.pop(),
        selection_from=settings.SITE.demo_date(-120),
        selection_until=settings.SITE.demo_date(-20),
        start_date=settings.SITE.demo_date(10),
        sector=SECTORS.pop(),
        function=FUNCTIONS.pop())
    yield obj

    # reset SECTORS and FUNCTIONS
    SECTORS = Cycler(cv.Sector.objects.all())
    FUNCTIONS = Cycler(cv.Function.objects.all())

    for i in range(30):
        yield jobs.Candidature(
            person=CLIENTS.pop(),
            state=CSTATES.pop(),
            date_submitted=settings.SITE.demo_date(-20 + i * 2),
            sector=SECTORS.pop(),
            function=FUNCTIONS.pop(),
        )

    COUNTRIES = Cycler(countries.Country.objects.all())
    COMPANIES = Cycler(Company.objects.all())

    # reset SECTORS and FUNCTIONS
    SECTORS = Cycler(cv.Sector.objects.all())
    FUNCTIONS = Cycler(cv.Function.objects.all())
    DURATIONS = Cycler([1, 2, 3, 6, 6, 9, 12, 12, 24, 24])  # months
    STATES = Cycler(cv.EducationEntryStates.items())

    for i in range(30):
        start_date = settings.SITE.demo_date(-1200 + i * 2)
        d = DURATIONS.pop()
        end_date = DurationUnits.months.add_duration(start_date, d)
        yield cv.Experience(
            person=CLIENTS.pop(),
            company=COMPANIES.pop(),
            country=COUNTRIES.pop(),
            start_date=start_date,
            end_date=end_date,
            sector=SECTORS.pop(),
            function=FUNCTIONS.pop(),
        )

    TRAINING_TYPES = Cycler(cv.StudyType.objects.filter(is_training=True))
    for i in range(20):
        start_date = settings.SITE.demo_date(-1200 + i * 2)
        d = DURATIONS.pop()
        end_date = DurationUnits.months.add_duration(start_date, d)
        yield cv.Training(
            person=CLIENTS.pop(),
            type=TRAINING_TYPES.pop(),
            school=SCHOOLS.pop(),
            country=COUNTRIES.pop(),
            start_date=start_date,
            end_date=end_date,
            sector=SECTORS.pop(),
            function=FUNCTIONS.pop(),
            state=STATES.pop(),
        )

    STUDY_TYPES = Cycler(cv.StudyType.objects.filter(is_study=True))
    EDULEVELS = Cycler(cv.EducationLevel.objects.all())
    for i in range(20):
        start_date = settings.SITE.demo_date(-1200 + i * 2)
        d = DURATIONS.pop()
        end_date = DurationUnits.months.add_duration(start_date, d)
        yield cv.Study(
            person=CLIENTS.pop(),
            type=STUDY_TYPES.pop(),
            school=SCHOOLS.pop(),
            country=COUNTRIES.pop(),
            start_date=start_date,
            end_date=end_date,
            state=STATES.pop(),
            education_level=EDULEVELS.pop(),
        )


    #~ baker = Properties.objects.get(pk=1)
    #~ baker.save()
    #~ yield baker

    """
    Distribute properties to persons. The distribution should be
    "randomly", but independant of site's language setting.
    """

    for i, p in enumerate(Client.objects.all()):
        if i % 2:
            country = belgium
        else:
            country = COUNTRIES.pop()
        p.birth_country_id = country
        p.nationality_id = country

        if i % 3:
            p.languageknowledge_set.create(
                language_id='eng', written='3', spoken='3')
        elif i % 5:
            p.languageknowledge_set.create(
                language_id='eng', written='4', spoken='4')
        if p.zip_code == '4700':
            p.languageknowledge_set.create(language_id='ger', native=True)
            if i % 2:
                p.languageknowledge_set.create(
                    language_id='fre', written='2', spoken='2')
            p.is_cpas = True
            #~ p.is_active = True
            #~ p.client_state = pcsw.ClientStates.coached
            #~ p.native_language_id = 'ger'
        p.save()

    for short_code, isocode in (
        ('B', 'BE'),
        ('D', 'DE'),
        ('F', 'FR'),
    ):
        c = countries.Country.objects.get(pk=isocode)
        c.short_code = short_code
        c.save()

    i = pcsw.Client.objects.order_by('name').__iter__()
    p = i.next()
    offset = 0
    for f in cv.Function.objects.all():
        yield jobs.Candidature(person=p, function=f, sector=f.sector,
                               #~ date_submitted=i2d(20111019))
                               date_submitted=settings.SITE.demo_date(offset))
        p = i.next()
        offset -= 1

    PERSONGROUPS = Cycler(pcsw.PersonGroup.objects.all())
    AGENTS_SCATTERED = Cycler(
        alicia, hubert, melanie, caroline, hubert, melanie, hubert, melanie)
    ENDINGS = Cycler(pcsw.CoachingEnding.objects.all())
    for client in pcsw.Client.objects.all():
        story = COACHING_STORIES.get(client.client_state)
        if story:
            if not client.group:
                client.group = PERSONGROUPS.pop()
                PERSONGROUPS.pop()
                # ~ for i in range(5-client.group.id): PERSONGROUPS.pop() #
                client.save()
            periods = story.pop()
            type = COACHINGTYPES.pop()
            for a, b, primary, ct in periods:
                if ct == CT_OTHER:
                    type = COACHINGTYPES.pop()
                elif ct == CT_GSS:
                    type = ASD
                elif ct == CT_INTEG:
                    type = DSBE
                kw = dict(client=client,
                          user=AGENTS_SCATTERED.pop(),
                          type=type,
                          primary=primary)
                if a is not None:
                    kw.update(start_date=settings.SITE.demo_date(a))
                if b is not None:
                    kw.update(end_date=settings.SITE.demo_date(b))
                    kw.update(ending=ENDINGS.pop())
                yield pcsw.Coaching(**kw)

    # every 10th partner is obsolete

    for i, p in enumerate(contacts.Partner.objects.all()):
        if i % 10 == 0:
            p.is_obsolete = True
            p.save()

    # The reception desk opens at 8am. 20 visitors have checked in,
    # half of which

    RECEPTION_CLIENTS = Cycler(reception.Clients.request(user=theresia))
    REASONS = Cycler(_("Urgent problem"), '', _("Complain"), _("Information"))
    today = settings.SITE.demo_date()
    now = datetime.datetime(today.year, today.month, today.day, 8, 0)
    for i in range(1, 20):
        obj = RECEPTION_CLIENTS.pop()
        now += datetime.timedelta(minutes=3 * i, seconds=3 * i)
        obj = reception.create_prompt_event(
            obj, obj,
            AGENTS.pop(),
            REASONS.pop(),
            settings.SITE.site_config.client_guestrole,
            now)
        yield obj

    # TODO: the following possibly causes more than one busy guest per
    # agent.
    qs = cal.Guest.objects.filter(waiting_since__isnull=False)
    busy_agents = set()
    for i, obj in enumerate(qs):
        busy_since = obj.waiting_since + \
            datetime.timedelta(minutes=2 * i, seconds=2 * i)
        if i % 3 == 0:
            obj.gone_since = busy_since + \
                datetime.timedelta(minutes=2 * i, seconds=3 * i)
            obj.state = cal.GuestStates.gone
        elif not obj.event.user in busy_agents:
            obj.busy_since = busy_since
            obj.state = cal.GuestStates.busy
            busy_agents.add(obj.event.user)

        yield obj

    Calendar = dd.resolve_model('cal.Calendar')
    COLORS = Cycler(Calendar.COLOR_CHOICES)

    for u in settings.SITE.user_model.objects.exclude(profile=None):
        obj = Calendar(name=u.username, color=COLORS.pop())
        yield obj
        u.calendar = obj
        u.save()

    # create a primary ClientAddress for each Client.
    # no longer needed. done by plausibility.fixtures.demo2
    # for obj in settings.SITE.modules.contacts.Partner.objects.all():
    #     obj.repairdata()

    # have partners speak different languages
    # most partners speak first language
    if len(settings.SITE.languages):
        ld = []  # language distribution
        ld = [settings.SITE.languages[0].django_code] * 10
        if len(settings.SITE.languages) > 1:
            ld += [settings.SITE.languages[1].django_code] * 3
            if len(settings.SITE.languages) > 2:
                ld += [settings.SITE.languages[2].django_code]
        LANGS = Cycler(ld)
        for obj in settings.SITE.modules.contacts.Partner.objects.all():
            obj.language = LANGS.pop()
            obj.save()
Example #47
0
    logger.info("Execute file %s ...", fn)
    six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args)
    # pmem()  # requires pip install psutil


def bv2kw(fieldname, values):
    """
    Needed if `Site.languages` changed between dumpdata and loaddata
    """
    return settings.SITE.babelkw(fieldname,
                                 en=values[0],
                                 de=values[1],
                                 fr=values[2])


dumps_Foo = resolve_model("dumps.Foo")


def create_dumps_foo(id, designation, last_visit, bar):
    #    if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar)
    kw = dict()
    kw.update(id=id)
    if designation is not None: kw.update(bv2kw('designation', designation))
    kw.update(last_visit=last_visit)
    kw.update(bar=bar)
    return dumps_Foo(**kw)


def main(args):
    loader = DpyLoader(globals(), quick=args.quick)
    from django.core.management import call_command
Example #48
0
    process = psutil.Process(os.getpid())
    print(process.memory_info().rss)
    
def execfile(fn, *args):
    logger.info("Execute file %s ...", fn)
    six.exec_(compile(open(fn, "rb").read(), fn, 'exec'), *args)
    # pmem()  # requires pip install psutil


def bv2kw(fieldname, values):
    """
    Needed if `Site.languages` changed between dumpdata and loaddata
    """
    return settings.SITE.babelkw(fieldname, en=values[0],de=values[1],fr=values[2])
    
dumps_Foo = resolve_model("dumps.Foo")


def create_dumps_foo(id, designation, last_visit, bar):
#    if bar: bar = settings.SITE.models.dumps.Bars.get_by_value(bar)
    kw = dict()
    kw.update(id=id)
    if designation is not None: kw.update(bv2kw('designation',designation))
    kw.update(last_visit=last_visit)
    kw.update(bar=bar)
    return dumps_Foo(**kw)




def main(args):
Example #49
0
def make_remote_field(model, name):
    parts = name.split('__')
    if len(parts) == 1:
        return
    # It's going to be a RemoteField
    # logger.warning("20151203 RemoteField %s in %s", name, cls)

    from lino.core import store
    cls = model
    field_chain = []
    editable = False
    for n in parts:
        if model is None:
            raise Exception(
                "Invalid remote field {0} for {1}".format(name, cls))

        if isinstance(model, six.string_types):
            # Django 1.9 no longer resolves the
            # rel.model of ForeignKeys on abstract
            # models, so we do it here.
            model = resolve_model(model)
            # logger.warning("20151203 %s", model)

        fld = model.get_data_elem(n)
        if fld is None:
            raise Exception(
                "Invalid RemoteField %s.%s (no field %s in %s)" %
                (full_model_name(model), name, n, full_model_name(model)))
        # make sure that the atomizer gets created.
        store.get_atomizer(model, fld, fld.name)
        field_chain.append(fld)
        if isinstance(fld, models.OneToOneRel):
            editable = True
        if getattr(fld, 'remote_field', None):
            model = fld.remote_field.model
        elif getattr(fld, 'rel', None):
            raise Exception("20180712")
            model = fld.rel.model
        else:
            model = None

    def getter(obj, ar=None):
        try:
            for fld in field_chain:
                if obj is None:
                    return None
                obj = fld._lino_atomizer.full_value_from_object(
                    obj, ar)
            return obj
        except Exception as e:
            # raise
            msg = "Error while computing {}: {} ({} in {})"
            raise Exception(msg.format(
                name, e, fld, field_chain))
            # ~ if False: # only for debugging
            if True:  # see 20130802
                logger.exception(e)
                return str(e)
            return None

    if not editable:
        return RemoteField(getter, name, fld)

    def setter(obj, value):
        # logger.info("20180712 %s setter() %s", name, value)
        # all intermediate fields are OneToOneRel
        target = obj
        try:
            for fld in field_chain:
                # print("20180712a %s" % fld)
                if isinstance(fld, models.OneToOneRel):
                    reltarget = getattr(target, fld.name, None)
                    if reltarget is None:
                        rkw = { fld.field.name: target}
                        # print(
                        #     "20180712 create {}({})".format(
                        #         fld.related_model, rkw))
                        reltarget = fld.related_model(**rkw)
                        reltarget.full_clean()
                        reltarget.save()

                    setattr(target, fld.name, reltarget)
                    target.full_clean()
                    target.save()
                    # print("20180712b {}.{} = {}".format(
                    #     target, fld.name, reltarget))
                    target = reltarget
                else:
                    setattr(target, fld.name, value)
                    target.full_clean()
                    target.save()
                    # print(
                    #     "20180712c setattr({},{},{}".format(
                    #         target, fld.name, value))
                    return True
        except Exception as e:
            raise e.__class__(
                "Error while setting %s: %s" % (name, e))
            # ~ if False: # only for debugging
            if True:  # see 20130802
                logger.exception(e)
                return str(e)
            return False

    return RemoteField(getter, name, fld, setter)
Example #50
0
#~ from lino.utils import crl2hex, hex2crl

from lino.utils import join_words
from lino_xl.lib.contacts.utils import name2kw, street2kw
#~ from lino_xl.lib.contacts.models import GENDER_MALE, GENDER_FEMALE
from lino.api import dd, rt
from lino.utils.instantiator import Instantiator

from lino.core.utils import resolve_model, obj2str
import lino

from lino.utils import confirm, iif
from lino.core.utils import app_labels
from lino_book.projects.crl.models import CRL

Country = resolve_model('countries.Country')
Place = resolve_model('countries.Place')
Person = resolve_model("contacts.Person")
Company = resolve_model("contacts.Company")


def parsedate(T):
    if not T:
        return
    T = T.replace('.', '')
    try:
        if len(T) == 4:
            return (datetime.date(int(T), 6, 30), True)
        elif len(T) == 6:
            return (datetime.date(int(T[:4]), int(T[4:6]), 15), True)
        elif len(T) == 8:
Example #51
0
 def on_site_startup(self, site):
     # print("votes.on_site_startup")
     self.votable_model = resolve_model(self.votable_model)
     super(Plugin, self).on_site_startup(site)
Example #52
0
 def on_site_startup(self, site):
     # print("votes.on_site_startup")
     self.votable_model = resolve_model(self.votable_model)
     super(Plugin, self).on_site_startup(site)
Example #53
0
def make_remote_field(model, name):
    parts = name.split('__')
    if len(parts) == 1:
        return
    # It's going to be a RemoteField
    # logger.warning("20151203 RemoteField %s in %s", name, cls)

    from lino.core import store
    cls = model
    field_chain = []
    editable = False
    leaf_chooser = None
    for n in parts:
        if model is None:
            return
            # raise Exception(
            #     "Invalid remote field {0} for {1}".format(name, cls))

        if isinstance(model, str):
            # Django 1.9 no longer resolves the
            # rel.model of ForeignKeys on abstract
            # models, so we do it here.
            model = resolve_model(model)
            # logger.warning("20151203 %s", model)

        fld = model.get_data_elem(n)
        if fld is None:
            return
            # raise Exception(
            #     "Invalid RemoteField %s.%s (no field %s in %s)" %
            #     (full_model_name(model), name, n, full_model_name(model)))

        # make sure that the atomizer gets created.
        store.get_atomizer(model, fld, fld.name)

        if isinstance(fld, VirtualField):
            fld.lino_resolve_type()
        leaf_chooser = choosers.check_for_chooser(model, fld)

        field_chain.append(fld)
        if isinstance(fld, models.OneToOneRel):
            editable = True
        if getattr(fld, 'remote_field', None):
            model = fld.remote_field.model
        else:
            model = None

    if leaf_chooser is not None:
        d = choosers.get_choosers_dict(cls)
        d[name] = leaf_chooser

    def getter(obj, ar=None):
        try:
            for fld in field_chain:
                if obj is None:
                    return None
                obj = fld._lino_atomizer.full_value_from_object(
                    obj, ar)
            return obj
        except Exception as e:
            # raise
            msg = "Error while computing {}: {} ({} in {})"
            raise Exception(msg.format(
                name, e, fld, field_chain))
            # ~ if False: # only for debugging
            if True:  # see 20130802
                logger.exception(e)
                return str(e)
            return None

    if not editable:
        rf = RemoteField(getter, name, fld)
        # choosers.check_for_chooser(model, rf)
        return rf

    def setter(obj, value):
        # logger.info("20180712 %s setter() %s", name, value)
        # all intermediate fields are OneToOneRel
        target = obj
        try:
            for fld in field_chain:
                # print("20180712a %s" % fld)
                if isinstance(fld, models.OneToOneRel):
                    reltarget = getattr(target, fld.name, None)
                    if reltarget is None:
                        rkw = { fld.field.name: target}
                        # print(
                        #     "20180712 create {}({})".format(
                        #         fld.related_model, rkw))
                        reltarget = fld.related_model(**rkw)
                        reltarget.full_clean()
                        reltarget.save()

                    setattr(target, fld.name, reltarget)
                    target.full_clean()
                    target.save()
                    # print("20180712b {}.{} = {}".format(
                    #     target, fld.name, reltarget))
                    target = reltarget
                else:
                    setattr(target, fld.name, value)
                    target.full_clean()
                    target.save()
                    # print(
                    #     "20180712c setattr({},{},{}".format(
                    #         target, fld.name, value))
                    return True
        except Exception as e:
            raise e.__class__(
                "Error while setting %s: %s" % (name, e))
            # ~ if False: # only for debugging
            if True:  # see 20130802
                logger.exception(e)
                return str(e)
            return False

    rf = RemoteField(getter, name, fld, setter)
    # choosers.check_for_chooser(model, rf)
    return rf
Example #54
0
 def attach_to_actor(self, actor, name):
     self.child_model = resolve_model(self.child_model)
     self._label = self.child_model._meta.verbose_name
     return super(ChildAction, self).attach_to_actor(actor, name)
Example #55
0
#~ print 20120225, 'settings.FIXTURE_DIRS is', settings.FIXTURE_DIRS

dblogger.info("Imported contacts demo fixture")

COUNT = 0

#~ addresstype= Instantiator('contacts.AddressType',"name").build
role = Instantiator('contacts.Role', "name").build
#~ person = Instantiator('contacts.Person',"first_name last_name").build
#~ company = Instantiator('contacts.Company',"name").build
#~ contact = Instantiator('contacts.Contact').build

Company = contacts.Company
Person = contacts.Person
User = contacts.User
City = resolve_model('countries.City')

if not settings.SITE.abstract_address:
    Address = contacts.Address
    address = Instantiator(
        Address, "country zip_code city:name street street_no").build


def company(name, country_id, zip_code, city, street, street_no):
    if settings.SITE.abstract_address:
        city = City.objects.get(name=city)
        yield Company(name=name, country_id=country_id, zip_code=zip_code,
                      city=city, street=street, street_no=street_no)
    else:
        addr = address(country_id, zip_code, city, street, street_no)
        yield addr
Example #56
0
 def attach_to_actor(self, actor, name):
     self.child_model = resolve_model(self.child_model)
     self.label = self.child_model._meta.verbose_name
     return super(ChildAction, self).attach_to_actor(actor, name)
Example #57
0
import logging
logger = logging.getLogger(__name__)

#~ from django.utils import unittest
#~ from django.test.client import Client
#from lino.igen import models
#from lino_xl.lib.contacts.models import Contact, Companies
#from lino_xl.lib.countries.models import Country
#~ from lino_xl.lib.contacts.models import Companies

from lino.core.utils import resolve_model
#Companies = resolve_model('contacts.Companies')
from lino.utils.djangotest import TestCase

#~ Person = resolve_model('contacts.Person')
Invoice = resolve_model('sales.Invoice')
#~ Property = resolve_model('properties.Property')
#~ PersonProperty = resolve_model('properties.PersonProperty')


class DemoTest(TestCase):
    #~ fixtures = [ 'std','demo' ]
    fixtures = 'std few_countries few_languages few_cities demo'.split()


def test01(self):
    """
    """
    self.assertEqual(Invoice.objects.all().count(), 28)
    i = Invoice.objects.all()[0]
    self.assertEqual(str(i), u"Invoice # 1")
Example #58
0
    def get_data_elem(cls, name):
        """Return the named data element. This can be a database field, a
        :class:`lino.core.fields.RemoteField`, a
        :class:`lino.core.fields.VirtualField` or a Django-style
        virtual field (GenericForeignKey).

        """
        #~ logger.info("20120202 get_data_elem %r,%r",model,name)
        if not name.startswith('__'):
            parts = name.split('__')
            if len(parts) > 1:
                # It's going to be a RemoteField
                # logger.warning("20151203 RemoteField %s in %s", name, cls)

                from lino.core import store

                model = cls
                field_chain = []
                editable = False
                for n in parts:
                    if model is None:
                        raise Exception(
                            "Invalid remote field {0} for {1}".format(
                                name, cls))

                    if isinstance(model, six.string_types):
                        # Django 1.9 no longer resolves the
                        # rel.model of ForeignKeys on abstract
                        # models, so we do it here.
                        model = resolve_model(model)
                        # logger.warning("20151203 %s", model)

                    fld = model.get_data_elem(n)
                    if fld is None:
                        raise Exception(
                            "Invalid RemoteField %s.%s (no field %s in %s)" %
                            (full_model_name(model), name, n,
                             full_model_name(model)))
                    # make sure that the atomizer gets created.
                    store.get_atomizer(model, fld, fld.name)
                    field_chain.append(fld)
                    if isinstance(fld, models.OneToOneRel):
                        editable = True
                    if getattr(fld, 'remote_field', None):
                        model = fld.remote_field.model
                    elif getattr(fld, 'rel', None):
                        raise Exception("20180712")
                        model = fld.rel.model
                    else:
                        model = None

                def getter(obj, ar=None):
                    try:
                        for fld in field_chain:
                            if obj is None:
                                return None
                            obj = fld._lino_atomizer.full_value_from_object(
                                obj, ar)
                        return obj
                    except Exception as e:
                        # raise
                        msg = "Error while computing {}: {} ({} in {})"
                        raise Exception(msg.format(name, e, fld, field_chain))
                        # ~ if False: # only for debugging
                        if True:  # see 20130802
                            logger.exception(e)
                            return str(e)
                        return None

                if not editable:
                    return fields.RemoteField(getter, name, fld)

                def setter(obj, value):
                    # logger.info("20180712 %s setter() %s", name, value)
                    # all intermediate fields are OneToOneRel
                    target = obj
                    try:
                        for fld in field_chain:
                            # print("20180712a %s" % fld)
                            if isinstance(fld, models.OneToOneRel):
                                reltarget = getattr(target, fld.name, None)
                                if reltarget is None:
                                    rkw = {fld.field.name: target}
                                    # print(
                                    #     "20180712 create {}({})".format(
                                    #         fld.related_model, rkw))
                                    reltarget = fld.related_model(**rkw)
                                    reltarget.full_clean()
                                    reltarget.save()

                                setattr(target, fld.name, reltarget)
                                target.full_clean()
                                target.save()
                                # print("20180712b {}.{} = {}".format(
                                #     target, fld.name, reltarget))
                                target = reltarget
                            else:
                                setattr(target, fld.name, value)
                                target.full_clean()
                                target.save()
                                # print(
                                #     "20180712c setattr({},{},{}".format(
                                #         target, fld.name, value))
                                return True
                    except Exception as e:
                        raise Exception("Error while setting %s: %s" %
                                        (name, e))
                        # ~ if False: # only for debugging
                        if True:  # see 20130802
                            logger.exception(e)
                            return str(e)
                        return False

                return fields.RemoteField(getter, name, fld, setter)

        try:
            return cls._meta.get_field(name)
        except models.FieldDoesNotExist:
            pass

        v = get_class_attr(cls, name)
        if v is not None:
            return v

        for vf in cls._meta.private_fields:
            if vf.name == name:
                return vf