Azima
Azima

Reputation: 4151

django all fields not appearing in admin form

I have following model in django:

class ProjectScheme(models.Model):
    name = models.CharField(max_length=250, blank=False,null=False)
    parent_scheme_id = models.ForeignKey(ProjectSchemeMaster, on_delete = models.CASCADE)
    rule = models.TextField(blank=True)
    created_on = models.DateTimeField(auto_now=False, auto_now_add=True)
    created_by = models.IntegerField(blank=True,null=True)
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
    updated_by = models.IntegerField(blank=True,null=True)

    def __str__(self):
        return str(self.name)

And in admin.py

# Register your models here.
class ProjectSchemeAdmin(admin.ModelAdmin):
    exclude = ('id',)

    class Meta:
        model = ProjectScheme

admin.site.register(ProjectScheme, ProjectSchemeAdmin)

But date fields: updated_on, created_on don't show up on admin form. enter image description here

I also tried without ProjectSchemeAdmin class, and also:

class ProjectSchemeAdmin(admin.ModelAdmin):
    pass

Also,

# list_display = [field.name for field in ProjectScheme._meta.fields if field.name != "id"]
list_display = ["id", "name","parent_scheme_id","rule","created_on", "created_by","updated_on","updated_by"]

But the same.

I need to get all the fields in admin form.

Upvotes: 1

Views: 1321

Answers (1)

Bishwo Adhikari
Bishwo Adhikari

Reputation: 93

You need to add readonly_fields = ('created_on','updated_on') to display the date field.

# Register your models here.
class ProjectSchemeAdmin(admin.ModelAdmin):
    list_display = ["name","parent_scheme_id","rule","created_on", "created_by","updated_on","updated_by"]
    readonly_fields = ('created_on','updated_on') 

    class Meta:
        model = ProjectScheme

admin.site.register(ProjectScheme, ProjectSchemeAdmin)

As mentioned in the docs:

As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.

The value auto_now_add is True. So no matter what date value you enter via admin UI, it will ultimately be overriden, which means there is no reason to display the field. In this case, as you need to display the field anyway, adding the readonly_fields does the trick.

Hope this helps!

Upvotes: 1

Related Questions