pub_date field is not visible in admin panel, even after configuring the app made migrations i tried every way possible from my side

47 views
Skip to first unread message

Likhith K.P.

unread,
May 31, 2023, 10:03:09 AM5/31/23
to Django users
from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length = 500)
    pub_date = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete = models.CASCADE)
    choice_text = models.CharField( max_length = 200)
    votes = models.IntegerField(default = 0)

    def __str__(self):
        return self.choice_text

Ryan Nowakowski

unread,
May 31, 2023, 11:15:56 AM5/31/23
to Django users
auto_now_add automatically sets editable=False[1]. When editable=False,
the field isn't displayed in the admin[2]. To show these fields in the
admin but leave them non-editable, list them as read-only fields[3] like
this:

# admin.py
from .models import Question

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
readonly_fields = ['pub_date']


If you want these auto_now_add fields to be in the admin and editable,
I'm not sure, I've never done this. Maybe you can't explicitly set
editable=True on the field? Usually if I want to set a DateTime
automatically and also make it editable, I won't use auto_add_now.
Instead I'll override the save method and set the field there.


[1] https://docs.djangoproject.com/en/4.2/ref/models/fields/#datefield
[2] https://docs.djangoproject.com/en/4.2/ref/models/fields/#editable
[3] https://docs.djangoproject.com/en/4.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f8a5d278-a840-433b-b431-9499d9dd9debn%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages