Tuesday 16 July 2013

Display AutoField(primary_key) as read only in Django admin

Generally It doesn't have an ID until you save it.


Please follow below code it will sure help you to overcome from None.

models.py
class A(models.Model):
    a = models.AutoField(primary_key=True)
   
    def __str__(self):
        return str(self.a)

admin.py 
class AAdmin(admin.ModelAdmin):
    list_display = ['a']
    readonly_fields = ['ass']

    def ass(self, obj):
        if obj.a is None:
            a = A.objects.all().order_by('-a')[:1]
            print a
            if a:
                return a[0].a + 1
            else:
                return 0
        else:
            return obj.a
admin.site.register(A, AAdmin)



Please check above code .if any issue please revert me.


Prashant Gaur
+91 9030015491