Mario Orlandi's Snippets

01/12/2011

list_display item with attributes in ModelAdmin

Filed under: Uncategorized — Tags: , — morlandi @ 12:58

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', ... 'format_date_modified', )

    def format_date_modified(self, obj):
        return obj.date_modified.strftime('%Y-%m-%d %H:%M:%S')
    format_date_modified.short_description = _(u'Date modified')
    format_date_modified.admin_order_field = 'date_modified'
    format_date_modified.allow_tags = True
    #format_date_modified.boolean = False

28/10/2011

Allow Bi-Directional ManyToMany in Django Admin

Filed under: Uncategorized — Tags: , — morlandi @ 07:53
class Node(BaseEasyTree, PaintdbBaseModel):
    ...                
    pigments = models.ManyToManyField('Pigment', blank=True, verbose_name=_(u'Related pigments') )
                
class Pigment(PaintdbBaseModel):
    ...
    # Allow Bi-Directional ManyToMany in Admin as suggested here: https://code.djangoproject.com/ticket/897#comment:28
    #TODO: check South behaviour; probably a fake migration is needed
    nodes = models.ManyToManyField(Node, through=Node.pigments.through, blank=True, verbose_name=_(u'Related products'), related_name='node_pigments', )
 
class PigmentAdmin(PaintdbBaseModelAdmin):
    ...
    filter_horizontal = ('nodes',)
    ...
    fieldsets = (
        ...
        (_('Relations'), {'fields': ('nodes', )}),
        ...
    ...
    # eventually filter related elements
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "nodes":
            kwargs["queryset"] = Node.objects.for_user(request)
        return super(PigmentAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.