Exemplo n.º 1
0
    def run(self, model, fields, file_name, **kwargs):
        """Create the xls file"""
        if issubclass(model, TendenciBaseModel):
            fields = fields + (
                'allow_anonymous_view',
                'allow_user_view',
                'allow_member_view',
                'allow_user_edit',
                'allow_member_edit',
                'create_dt',
                'update_dt',
                'creator',
                'creator_username',
                'owner',
                'owner_username',
                'status',
                'status_detail',
            )

        items = model.objects.filter(status=True)
        data_row_list = []
        for item in items:
            # get the available fields from the model's meta
            opts = item._meta
            d = {}
            for f in opts.fields + opts.many_to_many:
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = [
                            "%s" % obj for obj in f.value_from_object(item)
                        ]
                    if isinstance(f, ForeignKey):
                        value = getattr(item, f.name)
                    if isinstance(f, GenericRelation):
                        generics = f.value_from_object(item).all()
                        value = ["%s" % obj for obj in generics]
                    if isinstance(f, DateTimeField):
                        if f.value_from_object(item):
                            value = f.value_from_object(item).strftime(
                                "%Y-%m-%d %H:%M")
                    else:
                        value = f.value_from_object(item)
                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = str(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 2
0
    def run(self, **kwargs):
        """Create the xls file"""
        form_fields = [
            'title',
            'slug',
            'intro',
            'response',
            'email_text',
            'subject_template',
            'send_email',
            'email_from',
            'email_copies',
            'completion_url',
            'custom_payment',
            'payment_methods',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        field_fields = [
            'label',
            'field_type',
            'field_function',
            'required',
            'visible',
            'choices',
            'position',
            'default',
        ]
        pricing_fields = [
            'label',
            'price',
        ]

        forms = Form.objects.filter(status=True)
        max_fields = forms.annotate(num_fields=Count('fields')).aggregate(
            Max('num_fields'))['num_fields__max']
        max_pricings = forms.annotate(num_pricings=Count('pricing')).aggregate(
            Max('num_pricings'))['num_pricings__max']
        file_name = 'forms.csv'
        data_row_list = []

        for form in forms:
            data_row = []
            # form setup
            form_d = full_model_to_dict(form)
            for field in form_fields:
                if field == 'payment_methods':
                    value = [m.human_name for m in form.payment_methods.all()]
                else:
                    value = form_d[field]
                value = str(value).replace(os.linesep, ' ').rstrip()
                value = escape_csv(value)
                data_row.append(value)

            if form.fields.all():
                # field setup
                for field in form.fields.all():
                    field_d = full_model_to_dict(field)
                    for f in field_fields:
                        value = field_d[f]
                        value = str(value).replace(os.linesep, ' ').rstrip()
                        value = escape_csv(value)
                        data_row.append(value)

            # fill out the rest of the field columns
            if form.fields.all().count() < max_fields:
                for i in range(0, max_fields - form.fields.all().count()):
                    for f in field_fields:
                        data_row.append('')

            if form.pricing_set.all():
                # field setup
                for pricing in form.pricing_set.all():
                    pricing_d = full_model_to_dict(pricing)
                    for f in pricing_fields:
                        value = pricing_d[f]
                        value = str(value).replace(os.linesep, ' ').rstrip()
                        value = escape_csv(value)
                        data_row.append(value)

            # fill out the rest of the field columns
            if form.pricing_set.all().count() < max_pricings:
                for i in range(0,
                               max_pricings - form.pricing_set.all().count()):
                    for f in pricing_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = form_fields
        for i in range(0, max_fields):
            fields = fields + ["field %s %s" % (i, f) for f in field_fields]
        for i in range(0, max_pricings):
            fields = fields + [
                "pricing %s %s" % (i, f) for f in pricing_fields
            ]
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 3
0
    def run(self, model, fields, file_name, **kwargs):
        """Create the xls file"""
        if issubclass(model, TendenciBaseModel):
            fields = fields + [
                'allow_anonymous_view',
                'allow_user_view',
                'allow_member_view',
                'allow_user_edit',
                'allow_member_edit',
                'create_dt',
                'update_dt',
                'creator',
                'creator_username',
                'owner',
                'owner_username',
                'status',
                'status_detail',
            ]

        items = model.objects.filter(status=True)
        start_dt = kwargs.get('start_dt', None)
        end_dt = kwargs.get('end_dt', None)
        include_files = kwargs.get('include_files', None)
        if start_dt and end_dt:
            if start_dt:
                try:
                    start_dt = datetime.strptime(start_dt, '%m/%d/%Y')
                except:
                    raise Exception(
                        'Please use the following date format MM/DD/YYYY.\n')

            if end_dt:
                try:
                    end_dt = datetime.strptime(end_dt, '%m/%d/%Y')
                    end_dt = end_dt + timedelta(days=1)
                except:
                    raise Exception(
                        'Please use the following date format MM/DD/YYYY.\n')
            if start_dt and end_dt:
                items = items.filter(update_dt__gte=start_dt,
                                     update_dt__lte=end_dt)
        data_row_list = []
        for item in items:
            # get the available fields from the model's meta
            opts = item._meta
            d = {}
            for f in opts.get_fields() + opts.many_to_many:
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = [
                            "%s" % obj for obj in f.value_from_object(item)
                        ]
                    elif isinstance(f, ForeignKey):
                        value = getattr(item, f.name)
                    elif isinstance(f, GenericRelation):
                        generics = f.value_from_object(item).all()
                        value = ["%s" % obj for obj in generics if obj != '']
                        value = ', '.join(value)
                    else:
                        value = f.value_from_object(item)
                        if value:
                            if isinstance(f, DateTimeField):
                                value = value.strftime("%Y-%m-%d %H:%M")
                            elif isinstance(f, DateField):
                                value = value.strftime("%Y-%m-%d")
                            elif isinstance(f, TimeField):
                                value = value.strftime('%H:%M:%S')

                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = str(d[field]).rstrip()
                value = escape_csv(value)
                data_row.append(value)

            data_row_list.append(data_row)

        if include_files:
            if model._meta.model_name == 'resume':
                temp_csv = NamedTemporaryFile(mode='w', delete=False)
                csv_writer = csv.writer(temp_csv, delimiter=',')
                csv_writer.writerow(fields)
                for data_row in data_row_list:
                    csv_writer.writerow(data_row)
                temp_csv.close()

                temp_zip = NamedTemporaryFile(mode='wb', delete=False)
                zip_fp = zipfile.ZipFile(temp_zip,
                                         'w',
                                         compression=zipfile.ZIP_DEFLATED)
                # handle files
                for item in items:
                    if item.resume_file:
                        zip_fp.write(item.resume_file.path,
                                     item.resume_file.name,
                                     zipfile.ZIP_DEFLATED)
                zip_fp.write(temp_csv.name, 'resumes.csv',
                             zipfile.ZIP_DEFLATED)
                zip_fp.close()
                temp_zip.close()

                # set the response for the zip files
                with open(temp_zip.name, 'rb') as f:
                    content = f.read()

                response = HttpResponse(content,
                                        content_type='application/zip')
                response[
                    'Content-Disposition'] = 'attachment; filename="export_resumes_%d.zip"' % time(
                    )

                # remove the temporary files
                unlink(temp_zip.name)
                unlink(temp_csv.name)

                return response

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 4
0
    def run(self, **kwargs):
        """Create the xls file"""
        nav_fields = [
            'title',
            'description',
            'megamenu',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        nav_item_fields = [
            'label',
            'title',
            'new_window',
            'css',
            'position',
            'level',
            'page',
            'url',
        ]

        navs = Nav.objects.filter(status=True)
        max_nav_items = navs.annotate(num_navitems=Count('navitem')).aggregate(
            Max('num_navitems'))['num_navitems__max']
        file_name = 'navs.csv'
        data_row_list = []

        for nav in navs:
            data_row = []
            # nav setup
            nav_d = full_model_to_dict(nav)
            for field in nav_fields:
                value = nav_d[field]
                value = unicode(value).replace(os.linesep, ' ').rstrip()
                data_row.append(value)

            if nav.navitem_set.all():
                # nav_item setup
                for nav_item in nav.navitem_set.all():
                    nav_item_d = full_model_to_dict(nav_item)
                    for field in nav_item_fields:
                        value = nav_item_d[field]
                        value = unicode(value).replace(os.linesep,
                                                       ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the nav_item columns
            if nav.navitem_set.all().count() < max_nav_items:
                for i in range(0,
                               max_nav_items - nav.navitem_set.all().count()):
                    for field in nav_item_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = nav_fields
        for i in range(0, max_nav_items):
            fields = fields + [
                "nav_item %s %s" % (i, f) for f in nav_item_fields
            ]
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 5
0
    def run(self, **kwargs):
        """Create the xls file"""
        event_fields = [
            'entity',
            'type',
            'title',
            'description',
            'all_day',
            'start_dt',
            'end_dt',
            'timezone',
            'private_slug',
            'password',
            'on_weekend',
            'external_url',
            'image',
            'tags',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        place_fields = [
            'name',
            'description',
            'address',
            'city',
            'state',
            'zip',
            'country',
            'url',
        ]
        configuration_fields = [
            'payment_method',
            'payment_required',
            'limit',
            'enabled',
            'is_guest_price',
            'use_custom_reg_form',
            'reg_form',
            'bind_reg_form_to_conf_only',
        ]
        speaker_fields = [
            'name',
            'description',
        ]
        organizer_fields = [
            'name',
            'description',
        ]
        pricing_fields = [
            'title',
            'quantity',
            'group',
            'price',
            'reg_form',
            'start_dt',
            'end_dt',
            'allow_anonymous',
            'allow_user',
            'allow_member',
            'status',
        ]

        events = Event.objects.filter(status=True)
        max_speakers = events.annotate(num_speakers=Count('speaker')).aggregate(Max('num_speakers'))['num_speakers__max']
        max_organizers = events.annotate(num_organizers=Count('organizer')).aggregate(Max('num_organizers'))['num_organizers__max']
        max_pricings = events.annotate(num_pricings=Count('registration_configuration__regconfpricing')).aggregate(Max('num_pricings'))['num_pricings__max']
        file_name = 'events.csv'
        data_row_list = []

        for event in events:
            data_row = []
            # event setup
            event_d = full_model_to_dict(event, fields=event_fields)
            for field in event_fields:
                value = None
                if field == 'entity':
                    if event.entity:
                        value = event.entity.entity_name
                elif field == 'type':
                    if event.type:
                        value = event.type.name
                elif field in event_d:
                    value = event_d[field]
                value = str(value).replace(os.linesep, ' ').rstrip()
                value = escape_csv(value)
                data_row.append(value)

            if event.place:
                # place setup
                place_d = full_model_to_dict(event.place)
                for field in place_fields:
                    value = place_d[field]
                    value = str(value).replace(os.linesep, ' ').rstrip()
                    value = escape_csv(value)
                    data_row.append(value)

            if event.registration_configuration:
                # config setup
                conf_d = full_model_to_dict(event.registration_configuration)
                for field in configuration_fields:
                    if field == "payment_method":
                        value = event.registration_configuration.payment_method.all()
                    else:
                        value = conf_d[field]
                    value = str(value).replace(os.linesep, ' ').rstrip()
                    value = escape_csv(value)
                    data_row.append(value)

            if event.speaker_set.all():
                # speaker setup
                for speaker in event.speaker_set.all():
                    speaker_d = full_model_to_dict(speaker)
                    for field in speaker_fields:
                        value = speaker_d[field]
                        value = str(value).replace(os.linesep, ' ').rstrip()
                        value = escape_csv(value)
                        data_row.append(value)

            # fill out the rest of the speaker columns
            if event.speaker_set.all().count() < max_speakers:
                for i in range(0, max_speakers - event.speaker_set.all().count()):
                    for field in speaker_fields:
                        data_row.append('')

            if event.organizer_set.all():
                # organizer setup
                for organizer in event.organizer_set.all():
                    organizer_d = full_model_to_dict(organizer)
                    for field in organizer_fields:
                        value = organizer_d[field]
                        value = str(value).replace(os.linesep, ' ').rstrip()
                        value = escape_csv(value)
                        data_row.append(value)

            # fill out the rest of the organizer columns
            if event.organizer_set.all().count() < max_organizers:
                for i in range(0, max_organizers - event.organizer_set.all().count()):
                    for field in organizer_fields:
                        data_row.append('')

            reg_conf = event.registration_configuration
            if reg_conf and reg_conf.regconfpricing_set.all():
                # pricing setup
                for pricing in reg_conf.regconfpricing_set.all():
                    pricing_d = full_model_to_dict(pricing)
                    for field in pricing_fields:
                        value = pricing_d[field]
                        value = str(value).replace(os.linesep, ' ').rstrip()
                        value = escape_csv(value)
                        data_row.append(value)

            # fill out the rest of the pricing columns
            if reg_conf and reg_conf.regconfpricing_set.all().count() < max_pricings:
                for i in range(0, max_pricings - reg_conf.regconfpricing_set.all().count()):
                    for field in pricing_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = event_fields + ["place %s" % f for f in place_fields]
        fields = fields + ["config %s" % f for f in configuration_fields]
        for i in range(0, max_speakers):
            fields = fields + ["speaker %s %s" % (i, f) for f in speaker_fields]
        for i in range(0, max_organizers):
            fields = fields + ["organizer %s %s" % (i, f) for f in organizer_fields]
        for i in range(0, max_pricings):
            fields = fields + ["pricing %s %s" % (i, f) for f in pricing_fields]
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 6
0
    def run(self, **kwargs):
        """Create the xls file"""
        event_fields = [
            'entity',
            'type',
            'title',
            'description',
            'all_day',
            'start_dt',
            'end_dt',
            'timezone',
            'private_slug',
            'password',
            'on_weekend',
            'external_url',
            'image',
            'tags',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        place_fields = [
            'name',
            'description',
            'address',
            'city',
            'state',
            'zip',
            'country',
            'url',
        ]
        configuration_fields = [
            'payment_method',
            'payment_required',
            'limit',
            'enabled',
            'is_guest_price',
            'use_custom_reg_form',
            'reg_form',
            'bind_reg_form_to_conf_only',
        ]
        speaker_fields = [
            'name',
            'description',
        ]
        organizer_fields = [
            'name',
            'description',
        ]
        pricing_fields = [
            'title',
            'quantity',
            'group',
            'price',
            'reg_form',
            'start_dt',
            'end_dt',
            'allow_anonymous',
            'allow_user',
            'allow_member',
            'status',
        ]

        events = Event.objects.filter(status=True)
        max_speakers = events.annotate(num_speakers=Count('speaker')).aggregate(Max('num_speakers'))['num_speakers__max']
        max_organizers = events.annotate(num_organizers=Count('organizer')).aggregate(Max('num_organizers'))['num_organizers__max']
        max_pricings = events.annotate(num_pricings=Count('registration_configuration__regconfpricing')).aggregate(Max('num_pricings'))['num_pricings__max']
        file_name = 'events.csv'
        data_row_list = []

        for event in events:
            data_row = []
            # event setup
            event_d = full_model_to_dict(event, fields=event_fields)
            for field in event_fields:
                value = None
                if field == 'entity':
                    if event.entity:
                        value = event.entity.entity_name
                elif field == 'type':
                    if event.type:
                        value = event.type.name
                elif field in event_d:
                    value = event_d[field]
                value = unicode(value).replace(os.linesep, ' ').rstrip()
                data_row.append(value)

            if event.place:
                # place setup
                place_d = full_model_to_dict(event.place)
                for field in place_fields:
                    value = place_d[field]
                    value = unicode(value).replace(os.linesep, ' ').rstrip()
                    data_row.append(value)

            if event.registration_configuration:
                # config setup
                conf_d = full_model_to_dict(event.registration_configuration)
                for field in configuration_fields:
                    if field == "payment_method":
                        value = event.registration_configuration.payment_method.all()
                    else:
                        value = conf_d[field]
                    value = unicode(value).replace(os.linesep, ' ').rstrip()
                    data_row.append(value)

            if event.speaker_set.all():
                # speaker setup
                for speaker in event.speaker_set.all():
                    speaker_d = full_model_to_dict(speaker)
                    for field in speaker_fields:
                        value = speaker_d[field]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the speaker columns
            if event.speaker_set.all().count() < max_speakers:
                for i in range(0, max_speakers - event.speaker_set.all().count()):
                    for field in speaker_fields:
                        data_row.append('')

            if event.organizer_set.all():
                # organizer setup
                for organizer in event.organizer_set.all():
                    organizer_d = full_model_to_dict(organizer)
                    for field in organizer_fields:
                        value = organizer_d[field]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the organizer columns
            if event.organizer_set.all().count() < max_organizers:
                for i in range(0, max_organizers - event.organizer_set.all().count()):
                    for field in organizer_fields:
                        data_row.append('')

            reg_conf = event.registration_configuration
            if reg_conf and reg_conf.regconfpricing_set.all():
                # pricing setup
                for pricing in reg_conf.regconfpricing_set.all():
                    pricing_d = full_model_to_dict(pricing)
                    for field in pricing_fields:
                        value = pricing_d[field]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the pricing columns
            if reg_conf and reg_conf.regconfpricing_set.all().count() < max_pricings:
                for i in range(0, max_pricings - reg_conf.regconfpricing_set.all().count()):
                    for field in pricing_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = event_fields + ["place %s" % f for f in place_fields]
        fields = fields + ["config %s" % f for f in configuration_fields]
        for i in range(0, max_speakers):
            fields = fields + ["speaker %s %s" % (i, f) for f in speaker_fields]
        for i in range(0, max_organizers):
            fields = fields + ["organizer %s %s" % (i, f) for f in organizer_fields]
        for i in range(0, max_pricings):
            fields = fields + ["pricing %s %s" % (i, f) for f in pricing_fields]
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 7
0
    def run(self, **kwargs):
        """Create the xls file"""
        form_fields = [
            'title',
            'slug',
            'intro',
            'response',
            'email_text',
            'subject_template',
            'send_email',
            'email_from',
            'email_copies',
            'completion_url',
            'custom_payment',
            'payment_methods',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        field_fields = [
            'label',
            'field_type',
            'field_function',
            'required',
            'visible',
            'choices',
            'position',
            'default',
        ]
        pricing_fields = [
            'label',
            'price',
        ]

        forms = Form.objects.filter(status=True)
        max_fields = forms.annotate(num_fields=Count('fields')).aggregate(Max('num_fields'))['num_fields__max']
        max_pricings = forms.annotate(num_pricings=Count('pricing')).aggregate(Max('num_pricings'))['num_pricings__max']
        file_name = 'forms.csv'
        data_row_list = []

        for form in forms:
            data_row = []
            # form setup
            form_d = full_model_to_dict(form)
            for field in form_fields:
                if field == 'payment_methods':
                    value = [m.human_name for m in form.payment_methods.all()]
                else:
                    value = form_d[field]
                value = unicode(value).replace(os.linesep, ' ').rstrip()
                data_row.append(value)

            if form.fields.all():
                # field setup
                for field in form.fields.all():
                    field_d = full_model_to_dict(field)
                    for f in field_fields:
                        value = field_d[f]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the field columns
            if form.fields.all().count() < max_fields:
                for i in range(0, max_fields - form.fields.all().count()):
                    for f in field_fields:
                        data_row.append('')

            if form.pricing_set.all():
                # field setup
                for pricing in form.pricing_set.all():
                    pricing_d = full_model_to_dict(pricing)
                    for f in pricing_fields:
                        value = pricing_d[f]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the field columns
            if form.pricing_set.all().count() < max_pricings:
                for i in range(0, max_pricings - form.pricing_set.all().count()):
                    for f in pricing_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = form_fields
        for i in range(0, max_fields):
            fields = fields + ["field %s %s" % (i, f) for f in field_fields]
        for i in range(0, max_pricings):
            fields = fields + ["pricing %s %s" % (i, f) for f in pricing_fields]
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 8
0
    def run(self, model, fields, file_name, **kwargs):
        """Create the xls file"""
        if issubclass(model, TendenciBaseModel):
            fields = fields + [
                'allow_anonymous_view',
                'allow_user_view',
                'allow_member_view',
                'allow_user_edit',
                'allow_member_edit',
                'create_dt',
                'update_dt',
                'creator',
                'creator_username',
                'owner',
                'owner_username',
                'status',
                'status_detail',
            ]

        items = model.objects.filter(status=True)
        start_dt = kwargs.get('start_dt', None)
        end_dt = kwargs.get('end_dt', None)
        include_files = kwargs.get('include_files', None)
        if start_dt and end_dt:
            if start_dt:
                try:
                    start_dt = datetime.strptime(start_dt, '%m/%d/%Y')
                except:
                    raise Exception('Please use the following date format MM/DD/YYYY.\n')
    
            if end_dt:
                try:
                    end_dt = datetime.strptime(end_dt, '%m/%d/%Y')
                    end_dt = end_dt + timedelta(days=1)
                except:
                    raise Exception('Please use the following date format MM/DD/YYYY.\n')
            if start_dt and end_dt:
                items = items.filter(update_dt__gte=start_dt, update_dt__lte=end_dt)
        data_row_list = []
        for item in items:
            # get the available fields from the model's meta
            opts = item._meta
            d = {}
            for f in opts.fields + opts.many_to_many + tuple(opts.virtual_fields):
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = ["%s" % obj for obj in f.value_from_object(item)]
                    elif isinstance(f, ForeignKey):
                        value = getattr(item, f.name)
                    elif isinstance(f, GenericRelation):
                        generics = f.value_from_object(item).all()
                        value = ["%s" % obj for obj in generics]
                    else:
                        value = f.value_from_object(item)
                        if value:
                            if isinstance(f, DateTimeField):
                                value = value.strftime("%Y-%m-%d %H:%M")
                            elif isinstance(f, DateField):
                                value = value.strftime("%Y-%m-%d")
                            elif isinstance(f, TimeField):
                                value = value.strftime('%H:%M:%S')

                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = str(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)
            
        if include_files:
            if model._meta.model_name == 'resume':
                temp_csv = NamedTemporaryFile(mode='w', delete=False)
                csv_writer = csv.writer(temp_csv, delimiter=',')
                csv_writer.writerow(fields)
                for data_row in data_row_list:
                    csv_writer.writerow(data_row)
                temp_csv.close()
                
                temp_zip = NamedTemporaryFile(mode='wb', delete=False)
                zip_fp = zipfile.ZipFile(temp_zip, 'w', compression=zipfile.ZIP_DEFLATED)
                # handle files
                for item in items:
                    if item.resume_file:
                        zip_fp.write(item.resume_file.path, item.resume_file.name, zipfile.ZIP_DEFLATED)
                zip_fp.write(temp_csv.name, 'resumes.csv', zipfile.ZIP_DEFLATED)
                zip_fp.close()
                temp_zip.close()
                
                # set the response for the zip files
                with open(temp_zip.name, 'rb') as f:
                    content = f.read()
            
                response = HttpResponse(content, content_type='application/zip')
                response['Content-Disposition'] = 'attachment; filename="export_resumes_%d.zip"' % time()
    
                # remove the temporary files
                unlink(temp_zip.name)
                unlink(temp_csv.name)
                
                return response
                
        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 9
0
    def run(self, **kwargs):
        """Create the xls file"""
        fields = [
            'guid',
            'title',
            'slug',
            'header_image',
            'content',
            'view_contact_form',
            'design_notes',
            'syndicate',
            'template',
            'tags',
            'entity',
            'meta',
            'categories',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]

        file_name = 'pages.csv'

        pages = Page.objects.active()
        data_row_list = []
        for page in pages:
            # get the available fields from the model's meta
            opts = page._meta
            d = {}
            for f in opts.fields + opts.many_to_many:
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = [
                            "%s" % obj for obj in f.value_from_object(page)
                        ]
                    if isinstance(f, ForeignKey):
                        value = getattr(page, f.name)
                    if isinstance(f, GenericRelation):
                        generics = f.value_from_object(page).all()
                        value = ["%s" % obj for obj in generics]
                    else:
                        value = f.value_from_object(page)
                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = unicode(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 10
0
    def run(self, model, start_dt, end_dt, file_name, **kwargs):
        """Create the xls file"""
        fields = (
            'id',
            'guid',
            'object_type',
            'object_id',
            'title',
            'tender_date',
            'bill_to',
            'bill_to_first_name',
            'bill_to_last_name',
            'bill_to_company',
            'bill_to_address',
            'bill_to_city',
            'bill_to_state',
            'bill_to_zip_code',
            'bill_to_country',
            'bill_to_phone',
            'bill_to_fax',
            'bill_to_email',
            'ship_to',
            'ship_to_first_name',
            'ship_to_last_name',
            'ship_to_company',
            'ship_to_address',
            'ship_to_city',
            'ship_to_state',
            'ship_to_zip_code',
            'ship_to_country',
            'ship_to_phone',
            'ship_to_fax',
            'ship_to_email',
            'ship_to_address_type',
            'receipt',
            'gift',
            'arrival_date_time',
            'greeting',
            'instructions',
            'po',
            'terms',
            'due_date',
            'ship_date',
            'ship_via',
            'fob',
            'project',
            'other',
            'message',
            'subtotal',
            'shipping',
            'shipping_surcharge',
            'box_and_packing',
            'tax_exempt',
            'tax_exemptid',
            'tax_rate',
            'taxable',
            'tax',
            'variance',
            'discount_amount',
            'total',
            'payments_credits',
            'balance',
            'disclaimer',
            'variance_notes',
            'admin_notes',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status_detail',
            'status',
        )

        start_dt_date = datetime.strptime(start_dt, "%Y-%m-%d")
        end_dt_date = datetime.strptime(end_dt, "%Y-%m-%d")

        items = model.objects.filter(status=True, tender_date__gte=start_dt_date, tender_date__lte=end_dt_date)
        data_row_list = []
        for item in items:
            # get the available fields from the model's meta
            opts = item._meta
            d = {}
            for f in opts.fields + opts.many_to_many:
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = ["%s" % obj for obj in f.value_from_object(item)]
                    if isinstance(f, ForeignKey):
                        value = getattr(item, f.name)
                    if isinstance(f, GenericRelation):
                        generics = f.value_from_object(item).all()
                        value = ["%s" % obj for obj in generics]
                    if isinstance(f, DateTimeField):
                        if f.value_from_object(item):
                            value = f.value_from_object(item).strftime("%Y-%m-%d %H:%M")
                    else:
                        value = f.value_from_object(item)
                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = str(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 11
0
    def run(self, **kwargs):
        """Create the xls file"""
        fields = [
            'guid',
            'title',
            'slug',
            'header_image',
            'content',
            'view_contact_form',
            'design_notes',
            'syndicate',
            'template',
            'tags',
            'entity',
            'meta',
            'categories',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]

        file_name = 'pages.csv'

        pages = Page.objects.active()
        data_row_list = []
        for page in pages:
            # get the available fields from the model's meta
            opts = page._meta
            d = {}
            for f in opts.fields + opts.many_to_many:
                if f.name in fields: # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = ["%s" % obj for obj in f.value_from_object(page)]
                    if isinstance(f, ForeignKey):
                        value = getattr(page, f.name)
                    if isinstance(f, GenericRelation):
                        generics = f.value_from_object(page).all()
                        value = ["%s" % obj for obj in generics]
                    else:
                        value = f.value_from_object(page)
                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = unicode(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 12
0
    def run(self, model, start_dt, end_dt, file_name, **kwargs):
        """Create the xls file"""
        fields = (
            'id',
            'guid',
            'object_type',
            'object_id',
            'title',
            'tender_date',
            'bill_to',
            'bill_to_first_name',
            'bill_to_last_name',
            'bill_to_company',
            'bill_to_address',
            'bill_to_city',
            'bill_to_state',
            'bill_to_zip_code',
            'bill_to_country',
            'bill_to_phone',
            'bill_to_fax',
            'bill_to_email',
            'ship_to',
            'ship_to_first_name',
            'ship_to_last_name',
            'ship_to_company',
            'ship_to_address',
            'ship_to_city',
            'ship_to_state',
            'ship_to_zip_code',
            'ship_to_country',
            'ship_to_phone',
            'ship_to_fax',
            'ship_to_email',
            'ship_to_address_type',
            'receipt',
            'gift',
            'arrival_date_time',
            'greeting',
            'instructions',
            'po',
            'terms',
            'due_date',
            'ship_date',
            'ship_via',
            'fob',
            'project',
            'other',
            'message',
            'subtotal',
            'shipping',
            'shipping_surcharge',
            'box_and_packing',
            'tax_exempt',
            'tax_exemptid',
            'tax_rate',
            'taxable',
            'tax',
            'variance',
            'discount_amount',
            'total',
            'payments_credits',
            'balance',
            'disclaimer',
            'variance_notes',
            'admin_notes',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status_detail',
            'status',
        )

        start_dt_date = datetime.strptime(start_dt, "%Y-%m-%d")
        end_dt_date = datetime.strptime(end_dt, "%Y-%m-%d")

        items = model.objects.filter(status=True, tender_date__gte=start_dt_date, tender_date__lte=end_dt_date)
        data_row_list = []
        for item in items:
            # get the available fields from the model's meta
            opts = item._meta
            d = {}
            for f in opts.fields + opts.many_to_many:
                if f.name in fields:  # include specified fields only
                    if isinstance(f, ManyToManyField):
                        value = ["%s" % obj for obj in f.value_from_object(item)]
                    if isinstance(f, ForeignKey):
                        value = getattr(item, f.name)
                    if isinstance(f, GenericRelation):
                        generics = f.value_from_object(item).all()
                        value = ["%s" % obj for obj in generics]
                    if isinstance(f, DateTimeField):
                        if f.value_from_object(item):
                            value = f.value_from_object(item).strftime("%Y-%m-%d %H:%M")
                    else:
                        value = f.value_from_object(item)
                    d[f.name] = value

            # append the accumulated values as a data row
            # keep in mind the ordering of the fields
            data_row = []
            for field in fields:
                # clean the derived values into unicode
                value = unicode(d[field]).rstrip()
                data_row.append(value)

            data_row_list.append(data_row)

        return render_csv(file_name, fields, data_row_list)
Exemplo n.º 13
0
    def run(self, **kwargs):
        """Create the xls file"""
        nav_fields = [
            'title',
            'description',
            'megamenu',
            'allow_anonymous_view',
            'allow_user_view',
            'allow_member_view',
            'allow_user_edit',
            'allow_member_edit',
            'create_dt',
            'update_dt',
            'creator',
            'creator_username',
            'owner',
            'owner_username',
            'status',
            'status_detail',
        ]
        nav_item_fields = [
            'label',
            'title',
            'new_window',
            'css',
            'position',
            'level',
            'page',
            'url',
        ]

        navs = Nav.objects.filter(status=True)
        max_nav_items = navs.annotate(num_navitems=Count('navitem')).aggregate(Max('num_navitems'))['num_navitems__max']
        file_name = 'navs.csv'
        data_row_list = []

        for nav in navs:
            data_row = []
            # nav setup
            nav_d = full_model_to_dict(nav)
            for field in nav_fields:
                value = nav_d[field]
                value = unicode(value).replace(os.linesep, ' ').rstrip()
                data_row.append(value)

            if nav.navitem_set.all():
                # nav_item setup
                for nav_item in nav.navitem_set.all():
                    nav_item_d = full_model_to_dict(nav_item)
                    for field in nav_item_fields:
                        value = nav_item_d[field]
                        value = unicode(value).replace(os.linesep, ' ').rstrip()
                        data_row.append(value)

            # fill out the rest of the nav_item columns
            if nav.navitem_set.all().count() < max_nav_items:
                for i in range(0, max_nav_items - nav.navitem_set.all().count()):
                    for field in nav_item_fields:
                        data_row.append('')

            data_row_list.append(data_row)

        fields = nav_fields
        for i in range(0, max_nav_items):
            fields = fields + ["nav_item %s %s" % (i, f) for f in nav_item_fields]
        return render_csv(file_name, fields, data_row_list)