def test_related_name(self): """ Regression test for #13963 """ self.assertEquals(label_for_field("location", Event, return_attr=True), ("location", None)) self.assertEquals(label_for_field("event", Location, return_attr=True), ("awesome event", None)) self.assertEquals(label_for_field("guest", Event, return_attr=True), ("awesome guest", None))
def get_label_for_field(field_name, model, objects): from django.db.models import get_model if '.' in field_name: obj, field = get_field_value(objects[0], field_name, return_field = True) return label_for_field(field, get_model(obj._meta.app_label, obj._meta.object_name)) else: return label_for_field(field_name, model)
def test_list_label_abc(self): # Ensure model data is correct self.assertEqual(ConcreteModel._translations_model._meta.get_field_by_name('tr_title')[0].verbose_name, "Translated Title") # See that the TranslatedFieldDescriptor of the concrete model properly routes to the proper model self.assertEqual(label_for_field('tr_title', ConcreteModel), "Translated Title") # See that the TranslatedFieldDescriptor of the abstract model handles the fallback properly. self.assertEqual(label_for_field('tr_title', AbstractModel), "Tr title")
def result_headers(cl): result = ['id'] for field_name in cl.list_display: label = label_for_field(field_name, cl.model, model_admin = cl.model_admin) result.append(unicode(label)) return result
def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field('location', Event, return_attr=True), ('location', None), ) self.assertEqual( label_for_field('event', Location, return_attr=True), ('awesome event', None), ) self.assertEqual( label_for_field('guest', Event, return_attr=True), ('awesome guest', None), )
def result_headers(cl): lookup_opts = cl.lookup_opts for i, field_name in enumerate(cl.list_display): header, attr = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True) if attr: # if the field is the action checkbox: no sorting and special class if field_name == "action_checkbox": yield {"text": header, "class_attrib": mark_safe(' class="action-checkbox-column"')} continue header = pretty_name(header) # It is a non-field, but perhaps one that is sortable admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: yield {"text": header} continue # So this _is_ a sortable non-field. Go to the yield # after the else clause. else: admin_order_field = None th_classes = [] new_order_type = "asc" if field_name == cl.order_field or admin_order_field == cl.order_field: th_classes.append("sorted %sending" % cl.order_type.lower()) new_order_type = {"asc": "desc", "desc": "asc"}[cl.order_type.lower()] yield { "text": header, "sortable": True, "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), "class_attrib": mark_safe(th_classes and ' class="%s"' % " ".join(th_classes) or ""), }
def export_as_csv(modeladmin, request, queryset): response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=%s.csv' % unicode( modeladmin.opts).replace('.', '_') writer = csv.writer(response) if header: fields_header = [] for field_name in fields: text, attr = label_for_field(field_name, modeladmin.model, model_admin=modeladmin, return_attr=True) fields_header.append(text.capitalize()) writer.writerow(fields_header) for obj in queryset: line = [] for field_name in fields: f, attr, value = lookup_field(field_name, obj, modeladmin) if f is None or f.auto_created: result_repr = force_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(obj, f.name) if field_val is None: result_repr = '-' else: result_repr = field_val else: result_repr = display_for_field(value, f) line.append(strip_tags(result_repr)) writer.writerow(line) return response
def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field('location', Event, return_attr=True), ('location', None), ) self.assertEqual( label_for_field('event', Location, return_attr=True), ('awesome event', None), ) self.assertEqual( label_for_field('guest', Event, return_attr=True), ('awesome guest', None), )
def export_as_csv(modeladmin, request, queryset): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(modeladmin.opts).replace('.', '_') writer = csv.writer(response) if header: fields_header = [] for field_name in fields: text, attr = label_for_field( field_name, modeladmin.model, model_admin=modeladmin, return_attr=True ) fields_header.append(text.capitalize()) writer.writerow(fields_header) for obj in queryset: line = [] for field_name in fields: f, attr, value = lookup_field(field_name, obj, modeladmin) if f is None or f.auto_created: result_repr = force_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(obj, f.name) if field_val is None: result_repr = '-' else: result_repr = field_val else: result_repr = display_for_field(value, f) line.append(strip_tags(result_repr)) writer.writerow(line) return response
def __init__(self, parent_model, model_admin, **kwargs): if not issubclass(self.model, models.OrderableModel): raise ImproperlyConfigured("%s may only be used with OrderableModel models" % self.__class__.__name__) self.order_field = self.model.ordering_field self.order_field_label = label_for_field(self.model.ordering_field, self.model, model_admin) super(OrderableInline, self).__init__(parent_model, model_admin, **kwargs)
def export_model_as_csv(modeladmin, request, queryset): if hasattr(modeladmin, 'exportable_fields'): field_list = modeladmin.exportable_fields else: # Copy modeladmin.list_display to remove action_checkbox field_list = modeladmin.list_display[:] field_list.remove('action_checkbox') response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s-%s-export-%s.csv' % ( __package__.lower(), queryset.model.__name__.lower(), datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'), ) writer = csv.writer(response) writer.writerow( [admin_util.label_for_field(f, queryset.model, modeladmin) for f in field_list], ) for obj in queryset: csv_line_values = [] for field in field_list: field_obj, attr, value = admin_util.lookup_field(field, obj, modeladmin) csv_line_values.append(value) writer.writerow(csv_line_values) return response
def export_model_as_csv(modeladmin, request, queryset): if hasattr(modeladmin, 'exportable_fields'): field_list = modeladmin.exportable_fields else: # Copy modeladmin.list_display to remove action_checkbox field_list = modeladmin.list_display[:] #field_list.remove('action_checkbox') response = HttpResponse(mimetype='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=%s-%s-export-%s.csv' % ( __package__.lower(), queryset.model.__name__.lower(), datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'), ) writer = csv.writer(response) writer.writerow([ admin_util.label_for_field(f, queryset.model, modeladmin) for f in field_list ], ) for obj in queryset: csv_line_values = [] for field in field_list: field_obj, attr, value = admin_util.lookup_field( field, obj, modeladmin) csv_line_values.append(value) writer.writerow(csv_line_values) return response
def export_as_csv(modeladmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ """ model = modeladmin.model if fields: field_names = set(fields) else: field_names = set([field.name for field in model._meta.fields]) if exclude: excludeset = set(exclude) field_names = field_names - excludeset response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % ( unicode(model._meta).replace('.', '_'),) writer = csv.writer(response) if header: write_encoded(writer, (label_for_field(field, model, modeladmin) for field in field_names)) for obj in queryset: write_encoded(writer, (lookup_field(field, obj, modeladmin)[2] for field in field_names)) return response
def export_model_as_excel(modeladmin, request, queryset): has_name_fields = [ 'village', 'cell', 'sector', 'health_centre', 'referral_hospital', 'district', 'province', 'role' ] is_date_fields = ['date_of_birth', 'dob', 'join_date'] workbook = xlwt.Workbook() sheet_name = "%s" % (queryset.model.__name__.lower(), ) sheet = workbook.add_sheet(sheet_name) if hasattr(modeladmin, 'exportable_fields'): field_list = modeladmin.exportable_fields #field_list = field_list.__add__(('village__code', 'cell__code', )) else: # Copy modeladmin.list_display to remove action_checkbox field_list = modeladmin.list_display[:] #field_list.remove('action_checkbox') response = HttpResponse(mimetype="application/ms-excel") response[ 'Content-Disposition'] = 'attachment; filename=%s.xls' % sheet_name row = col = 0 for f in field_list: if f.__contains__('__code'): sheet.write(row, col, f.upper()) else: sheet.write( row, col, admin_util.label_for_field(f, queryset.model, modeladmin).upper()) col = col + 1 row = row + 1 for obj in queryset: excel_line_values = [] col = 0 for field in field_list: if field.__contains__('__code'): field_obj, attr, value = admin_util.lookup_field( field.replace('__code', ''), obj, modeladmin) if value: value = value.code else: field_obj, attr, value = admin_util.lookup_field( field, obj, modeladmin) try: if field in has_name_fields: sheet.write(row, col, value.name) elif field in is_date_fields: sheet.write( row, col, "%d/%d/%d" % (value.day, value.month, value.year)) else: sheet.write(row, col, value) except Exception, e: try: sheet.write(row, col, value) except: sheet.write(row, col, "NULL") col = col + 1 row = row + 1
def test_list_label(self): # Ensure model data is correct self.assertEqual(SimpleModel._translations_model._meta.get_field_by_name('tr_title')[0].verbose_name, "Translated Title") # See that adding a field to the admin list_display also receives the translated title # This happens by TranslatedFieldDescriptor.short_description self.assertEqual(label_for_field('tr_title', SimpleModel), "Translated Title")
def items(self): for f in self.fields: try: key = label_for_field(f.field, self.user) value = f.serializer.to_html(self.user, f.field) yield key, value except AttributeError: # TODO: Should it be ignored? pass
def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} label = label_for_field(self.model.ordering_field, self.model, model_admin=self) extra_context.update({ 'ordering_field': self.model.ordering_field, 'ordering_field_label': label }) return super(OrderableAdmin, self).changelist_view(request, extra_context)
def __init__(self, field, instance): if callable(field): class_name = field.__name__ != '<lambda>' and field.__name__ or '' else: class_name = field self.name = class_name self.label = label_for_field(field, instance.__class__) self.field_repr = get_field_value(field, instance) self.help_text = get_field_attr(field, instance, "help_text", "")
def result_headers(cl): """ Generates the list column headers. """ lookup_opts = cl.lookup_opts for i, field_name in enumerate(cl.list_display): header, attr = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True) if attr: # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": header, "class_attrib": mark_safe(' class="action-checkbox-column"') } continue # It is a non-field, but perhaps one that is sortable admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: yield {"text": header} continue # So this _is_ a sortable non-field. Go to the yield # after the else clause. else: admin_order_field = None th_classes = [] new_order_type = 'asc' if field_name == cl.order_field or admin_order_field == cl.order_field: th_classes.append('sorted %sending' % cl.order_type.lower()) new_order_type = { 'asc': 'desc', 'desc': 'asc' }[cl.order_type.lower()] yield { "text": header, "sortable": True, "url": cl.get_query_string({ ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type }), "class_attrib": mark_safe(th_classes and ' class="%s"' % ' '.join(th_classes) or '') }
def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: label = label_for_field(field, self.opts.model, self.model_admin) yield (False, forms.forms.pretty_name(label)) else: field = self.formset.form.base_fields[field] yield (field.widget.is_hidden, field.label)
def result_headers_csv(cl): """ Generates the list column headers. """ ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True) yield {"text": text}
def label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" name = forms.forms.pretty_name( label_for_field(self.field, self.model_admin.model, self.model_admin)) contents = force_unicode(escape(name)) + u":" return mark_safe('<label%(attrs)s>%(contents)s</label>' % { "attrs": flatatt(attrs), "contents": contents, })
def fields(self): for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if field in self.readonly_fields: yield { 'label': label_for_field(field, self.opts.model, self.opts), 'widget': { 'is_hidden': False }, 'required': False } else: yield self.formset.form.base_fields[field]
def label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" name = forms.forms.pretty_name( label_for_field(self.field, self.model_admin.model, self.model_admin) ) contents = force_unicode(escape(name)) + u":" return mark_safe('<label%(attrs)s>%(contents)s</label>' % { "attrs": flatatt(attrs), "contents": contents, })
def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: label = label_for_field(field, self.opts.model, self.model_admin) yield (False, forms.forms.pretty_name(label)) else: field = self.formset.form.base_fields[field] yield (field.widget.is_hidden, field.label)
def export_as_csv(modeladmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ and /2020/ """ header = True # TODO Also create export_as_csv for exporting all columns including list_display if not request.user.is_staff: raise PermissionDenied opts = modeladmin.model._meta field_names = modeladmin.list_display if 'action_checkbox' in field_names: field_names.remove('action_checkbox') response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode( opts).replace('.', '_') writer = csv.writer(response) if header: headers = [] for field_name in list(field_names): label = str( label_for_field(field_name, modeladmin.model, modeladmin)) #print 'label is: ', label if str.islower(label): label = str.title(label) headers.append(label) writer.writerow(headers) for row in queryset: #print 'trace row:', row values = [] for field in field_names: #print 'trace field:', field if field[:8] == 'link_to_': field = field[8:] value = (getattr(row, field)) if callable(value): try: value = value() or '' except: value = 'Error retrieving value' if value is None: value = '' #print 'trace value:', value values.append(unicode(value).encode('utf-8')) writer.writerow(values) return response # export_as_csv.short_description = description # return export_as_cs
def test_label_for_property(self): # NOTE: cannot use @property decorator, because of # AttributeError: 'property' object has no attribute 'short_description' class MockModelAdmin(object): def my_property(self): return "this if from property" my_property.short_description = 'property short description' test_from_property = property(my_property) self.assertEqual( label_for_field("test_from_property", Article, model_admin=MockModelAdmin), 'property short description' )
def test_label_for_property(self): # NOTE: cannot use @property decorator, because of # AttributeError: 'property' object has no attribute 'short_description' class MockModelAdmin(object): def my_property(self): return "this if from property" my_property.short_description = 'property short description' test_from_property = property(my_property) self.assertEqual( label_for_field("test_from_property", Article, model_admin=MockModelAdmin), 'property short description' )
def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: yield { "label": label_for_field(field, self.opts.model, self.opts), "widget": {"is_hidden": False}, "required": False, } else: yield self.formset.form.base_fields[field]
def get_change_column_form(self): choices = [ (field, (label_for_field(field, self.model, model_admin=self)).capitalize()) \ for field in self.list_display ] class AdjustableColumnsForm(forms.Form): columns = forms.MultipleChoiceField( choices=choices, widget=FilteredSelectMultiple('columns', False) ) return AdjustableColumnsForm
def __init__(self, queryset, display_fields=None, request=None, bordered=True, condensed=True, hover=True, striped=False, auto_append_padding_column=True): Table.__init__(self, bordered, condensed, hover, striped) self.queryset = queryset self.display_fields = display_fields or ('pk', '__unicode__') self.request = request self.model = queryset.model self.model_fields = {} append_padding_column = auto_append_padding_column for name in display_fields: attrs = {} if name in ('pk', 'id'): label = '#' attrs['class'] = 'id' elif callable(name): label = getattr(name, 'verbose_name', name.__name__) attrs['class'] = 'nowrap' else: label = label_for_field(name, self.model) try: field = self.queryset.model._meta.get_field_by_name( name)[0] if isinstance(field, models.TextField): if auto_append_padding_column: append_padding_column = False elif isinstance(field, models.DateField): attrs['class'] = 'datetime' elif isinstance(field, (models.IntegerField, models.FloatField, models.DecimalField)): attrs['class'] = 'number' else: attrs['class'] = 'nowrap' self.model_fields[name] = field except models.FieldDoesNotExist: pass self.add_column(label, name, attrs=attrs) if append_padding_column: self.add_column(None)
def export_as_csv(modeladmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ and /2020/ """ header = True # TODO Also create export_as_csv for exporting all columns including list_display if not request.user.is_staff: raise PermissionDenied opts = modeladmin.model._meta field_names = modeladmin.list_display if 'action_checkbox' in field_names: field_names.remove('action_checkbox') response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_') writer = csv.writer(response) if header: headers = [] for field_name in list(field_names): label = str(label_for_field(field_name,modeladmin.model,modeladmin)) #print 'label is: ', label if str.islower(label): label = str.title(label) headers.append(label) writer.writerow(headers) for row in queryset: #print 'trace row:', row values = [] for field in field_names: #print 'trace field:', field if field[:8] == 'link_to_': field= field[8:] value = (getattr(row, field)) if callable(value): try: value = value() or '' except: value = 'Error retrieving value' if value is None: value = '' #print 'trace value:', value values.append(unicode(value).encode('utf-8')) writer.writerow(values) return response # export_as_csv.short_description = description # return export_as_cs
def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: yield { 'label': label_for_field(field, self.opts.model, self.opts), 'widget': { 'is_hidden': False }, 'required': False } else: yield self.formset.form.base_fields[field]
def __init__(self, form, field, is_first, model_admin=None): label = label_for_field(field, form._meta.model, model_admin) # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. self.field = { 'name': force_unicode(label != '--' and label or ''), 'label': label, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True
def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: yield { 'label': label_for_field(field, self.opts.model, self.model_admin), 'widget': { 'is_hidden': False }, 'required': False } else: yield self.formset.form.base_fields[field]
def result_headers(cl): """ Generates the list column headers. """ lookup_opts = cl.lookup_opts for i, field_name in enumerate(cl.list_display): header, attr = label_for_field(field_name, cl.model, model_admin = cl.model_admin, return_attr = True ) if attr: # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": header, "class_attrib": mark_safe(' class="action-checkbox-column"') } continue # It is a non-field, but perhaps one that is sortable admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: yield {"text": header} continue # So this _is_ a sortable non-field. Go to the yield # after the else clause. else: admin_order_field = None th_classes = [] new_order_type = 'asc' if field_name == cl.order_field or admin_order_field == cl.order_field: th_classes.append('sorted %sending' % cl.order_type.lower()) new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()] # This is used to write a class hidden-phone for bootstrap2 if i > 3: th_classes.append('hidden-phone') yield { "text": header, "sortable": True, "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), "class_attrib": mark_safe(th_classes and ' class="%s"' % ' '.join(th_classes) or '') }
def labels(self): """ Get field label for fields """ if type(self.object_list) == type([]): model = self.formset.model else: model = self.object_list.model for field in self.visible_fields: name = None if self.formset: f = self.formset.empty_form.fields.get(field, None) if f: name = f.label if name is None: name = label_for_field(field, model) if name == model._meta.verbose_name: name = self.model_name and self.model_name or \ model._meta.verbose_name stype = None cur_sorted = False sortable = False if self.order_type: sortable = get_sort_field(field, model) stype = self.ASC # change order_type so that next sorting on the same # field will give reversed results if sortable and field == self.sort_field: cur_sorted = True if self.order_type == self.ASC: stype = self.DESC elif self.order_type == self.DESC: stype = self.ASC else: stype = self.ASC yield AdminListLabel(name, field, stype, cur_sorted, bool(sortable))
def exporta_a_csv(modeladmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ and /2020/ """ if not request.user.is_staff: raise PermissionDenied opts = modeladmin.model._meta field_names = modeladmin.list_display if 'action_checkbox' in field_names: field_names.remove('action_checkbox') # field_names = set([field.name for field in opts.fields]) # if fields: # fieldset = set(fields) # field_names = field_names & fieldset # elif exclude: # excludeset = set(exclude) # field_names = field_names - excludeset response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_') writer = csv.writer(response, delimiter=';') if header: headers = [] for field_name in list(field_names): label = label_for_field(field_name,modeladmin.model,modeladmin) if str.islower(label): label = str.title(label) headers.append(label) writer.writerow(headers) for row in queryset: values = [] for field in field_names: value = (getattr(row, field)) if callable(value): try: value = value() or '' except: value = 'Error retrieving value' if value is None: value = '' values.append(unicode(value).encode('utf-8')) writer.writerow(values) return response
def export_model_as_excel(modeladmin, request, queryset): has_name_fields = ['village', 'cell', 'sector', 'health_centre', 'referral_hospital', 'district', 'province','role'] is_date_fields = ['date_of_birth', 'dob', 'join_date'] workbook = xlwt.Workbook() sheet_name = "%s" % ( queryset.model.__name__.lower(), ) sheet = workbook.add_sheet(sheet_name) if hasattr(modeladmin, 'exportable_fields'): field_list = modeladmin.exportable_fields #field_list = field_list.__add__(('village__code', 'cell__code', )) else: # Copy modeladmin.list_display to remove action_checkbox field_list = modeladmin.list_display[:] #field_list.remove('action_checkbox') response = HttpResponse(mimetype = "application/ms-excel") response['Content-Disposition'] = 'attachment; filename=%s.xls' % sheet_name row = col = 0 for f in field_list: if f.__contains__('__code'): sheet.write(row , col, f.upper()) else: sheet.write(row , col, admin_util.label_for_field(f, queryset.model, modeladmin).upper()) col = col + 1 row = row + 1 for obj in queryset: excel_line_values = [] col = 0 for field in field_list: if field.__contains__('__code'): field_obj, attr, value = admin_util.lookup_field(field.replace('__code', ''), obj, modeladmin) if value: value = value.code else: field_obj, attr, value = admin_util.lookup_field(field, obj, modeladmin) try: if field in has_name_fields: sheet.write(row, col, value.name) elif field in is_date_fields: sheet.write(row, col, "%d/%d/%d" % (value.day, value.month, value.year)) else: sheet.write(row, col, value) except Exception, e: try: sheet.write(row, col, value) except: sheet.write(row, col, "NULL") col = col + 1 row = row + 1
def __init__(self, form, field, is_first, model_admin=None): label = label_for_field(field, form._meta.model, model_admin) # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ != '<lambda>' and field.__name__ or '' else: class_name = field self.field = { 'name': class_name, 'label': label, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True
def __init__(self, form, field, is_first, model_admin=None): label = label_for_field(field, form._meta.model, model_admin) # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ != '<lambda>' and field.__name__ or '' else: class_name = field self.field = { 'name': class_name, 'label': label, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True
def __init__(self, form, field, is_first, model_admin=None): label = label_for_field(field, form._meta.model, model_admin) # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ if field.__name__ != "<lambda>" else "" else: class_name = field self.field = { "name": class_name, "label": label, "field": field, "help_text": help_text_for_field(class_name, form._meta.model), } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True
def result_headers(cl): lookup_opts = cl.lookup_opts for i, field_name in enumerate(cl.list_display): attr = None try: f = lookup_opts.get_field(field_name) admin_order_field = None header = f.verbose_name except models.FieldDoesNotExist: header = label_for_field(field_name, cl.model, cl.model_admin) # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield {"text": header, "class_attrib": mark_safe(' class="action-checkbox-column"')} continue header = pretty_name(header) # It is a non-field, but perhaps one that is sortable admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: yield {"text": header} continue # So this _is_ a sortable non-field. Go to the yield # after the else clause. th_classes = [] new_order_type = 'asc' if field_name == cl.order_field or admin_order_field == cl.order_field: th_classes.append('sorted %sending' % cl.order_type.lower()) new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()] yield { "text": header, "sortable": True, "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), "class_attrib": mark_safe(th_classes and ' class="%s"' % ' '.join(th_classes) or '') }
def result_headers(cl): """ Generates the list column headers. """ ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field(field_name, cl.model, model_admin = cl.model_admin, return_attr = True ) if attr: # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": text, "class_attrib": mark_safe(' class="action-checkbox-column"'), "sortable": False, } continue admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: # Not sortable yield { "text": text, "class_attrib": format_html(' class="column-{0}"', field_name), "sortable": False, } continue # OK, it is sortable if we got this far th_classes = ['sortable', 'column-{0}'.format(field_name)] order_type = '' new_order_type = 'asc' sort_priority = 0 sorted = False # Is it currently being sorted on? if i in ordering_field_columns: sorted = True order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_primary = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_primary.insert(0, param) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_primary.append(param) o_list_toggle.append(param) o_list_remove.append(param) if i not in ordering_field_columns: o_list_primary.insert(0, make_qs_param(new_order_type, i)) yield { "text": text, "sortable": True, "sorted": sorted, "ascending": order_type == "asc", "sort_priority": sort_priority, "url_primary": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}), "url_remove": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}), "url_toggle": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), "class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '', }
def get_column_title(self, name): """Return the title of a column.""" return admin_util.label_for_field(name, self.model)
def header_list(self): u'''Возврвщает заголовки столбцов''' for i, field_name in enumerate(self.list_display): label = label_for_field(field_name, self.model) yield {'text': label}
def get_label(field): label = util.label_for_field(field, model, modeladmin) return force_unicode(label).title().encode('utf-8')
def test_label_for_field(self): """ Tests for label_for_field """ self.assertEqual(label_for_field("title", Article), "title") self.assertEqual(label_for_field("title2", Article), "another name") self.assertEqual(label_for_field("title2", Article, return_attr=True), ("another name", None)) self.assertEqual(label_for_field("__unicode__", Article), "article") self.assertEqual(label_for_field("__str__", Article), str("article")) self.assertRaises(AttributeError, lambda: label_for_field("unknown", Article)) def test_callable(obj): return "nothing" self.assertEqual(label_for_field(test_callable, Article), "Test callable") self.assertEqual( label_for_field(test_callable, Article, return_attr=True), ("Test callable", test_callable)) self.assertEqual(label_for_field("test_from_model", Article), "Test from model") self.assertEqual( label_for_field("test_from_model", Article, return_attr=True), ("Test from model", Article.test_from_model)) self.assertEqual( label_for_field("test_from_model_with_override", Article), "not What you Expect") self.assertEqual(label_for_field(lambda x: "nothing", Article), "--") class MockModelAdmin(object): def test_from_model(self, obj): return "nothing" test_from_model.short_description = "not Really the Model" self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin), "not Really the Model") self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin, return_attr=True), ("not Really the Model", MockModelAdmin.test_from_model))
def export_model_as_excel_xlsx(modeladmin, request, queryset): has_name_fields = ['village', 'cell', 'sector', 'health_centre', 'referral_hospital', 'district', 'province','role', 'type', 'location', 'nation'] is_date_fields = ['date_of_birth', 'dob', 'join_date', 'date', 'edd_date' , 'edd_anc2_date' , 'edd_anc3_date', 'edd_anc4_date' , 'edd_pnc1_date' , 'edd_pnc2_date' , 'edd_pnc3_date' ,'created'] is_person_fields = ['reporter', 'patient'] sheet_name = "%s" % ( queryset.model.__name__.lower(), ) # create a workbook in memory output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output) sheet = workbook.add_worksheet(sheet_name) if hasattr(modeladmin, 'exportable_fields'): field_list = modeladmin.exportable_fields else: # Copy modeladmin.list_display to remove action_checkbox field_list = modeladmin.list_display[:] #field_list.remove('action_checkbox') #response = HttpResponse(mimetype = "application/ms-excel") #response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % sheet_name row = col = 0 last_col = [] for f in field_list: sheet.write(row , col, admin_util.label_for_field(f, queryset.model, modeladmin).upper()) col = col + 1 row = row + 1 for obj in queryset: excel_line_values = [] col = 0 for field in field_list: field_obj, attr, value = admin_util.lookup_field(field, obj, modeladmin) try: if field in has_name_fields: sheet.write(row, col, value.name) elif field in is_date_fields: sheet.write(row, col, "%d/%d/%d" % (value.day, value.month, value.year)) elif field in is_person_fields: sheet.write(row, col, "%s" % (value.national_id)) else: sheet.write(row, col, value) except Exception, e: try: sheet.write(row, col, value) except: sheet.write(row, col, "NULL") col = col + 1 if queryset.model.__name__ == 'Report': details = obj.fields.all() #print row,col, "BEFORE" if details: for d in details: lc = [lc for lc in last_col if lc['name'] == d.type.key] mcol = col if lc: mcol = lc[0]['index']#;print mcol,d if d.type.has_value: sheet.write(row,mcol, d.value) else: sheet.write(row,mcol, d.type.description) else: li = [lc for lc in last_col if lc['index'] == col] if li: mcol = last_col[len(last_col)-1]['index']+1 #print mcol, d last_col.append({'name': d.type.key, 'index': mcol}) sheet.write(0, mcol, d.type.key) if d.type.has_value: sheet.write(row,mcol, d.value) else: sheet.write(row,mcol, d.type.description) col = col+1 #print last_col #print row,col, "AFTER" row = row + 1