views:

369

answers:

7
DECOM_CHOICES = (
    ('N', 'No'),
    ('Y', 'Yes'),
)

class Host(models.Model):
    hostname = models.CharField(max_length=36, unique=True)
    decommissioned = models.CharField(max_length=1, choices=DECOM_CHOICES, default='N')
    ip_address = models.IPAddressField()
    def __unicode__(self):
     return self.hostname

class HostAdmin(admin.ModelAdmin):
    fieldsets = [
     ('Host Info', {'fields': ['hostname','decommissioned','ip_address']}),
    list_display = ('hostname', 'ip_address', 'decommissioned')
    list_filter = ('decommissioned')

Now is there any way so that i can set decommissioned filter to 'N' by default instead of 'All'?

A: 

Looks like you're using code almost exactly from a Django ticket, which has a workaround in the comment for setting the default filter value. At present there's not a particularly elegant way to do this.

As an aside - wouldn't you be better of using a boolean field, since you're storing yes or no?

Dominic Rodger
A: 

this is similar to the ticket but if instead of two values then what can be done ? there should be some way .Many people say that they have done this

ha22109
A: 

I do this by modifying the GET data in the request object before passing it to changelist_view(). Not elegant, but it works.

class MyModelAdmin(admin.ModelAdmin):    
    def changelist_view(self, request, extra_context=None):
        if not request.GET.has_key('decommissioned__exact'):
            q = request.GET.copy()
            q['decommissioned__exact'] = 'N'
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)

Note: I haven't tried this exact code here, but you should get the idea.

Is there any way to make the 'All' link working with your solution ?
eugene y
A: 

the code works .GREAT.thanks

ha22109
A: 

the solution works but when i want to select all it cannot be selected

ha22109
A: 

if ('HTTP_REFERER' in request.META) and (request.META['HTTP_REFERER'].find('?') == -1) and (not request.GET.has_key('status__exact')):

Use this save condition instead of the given in the above sulution given by 'gerdemb' so that all can also be selected

ha22109
A: 

This won't work with multiple filters