Wednesday, May 31, 2023

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

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

On Wed, May 31, 2023 at 12:57:24AM -0700, Likhith K.P. wrote:
> 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
>
> --
> 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+unsubscribe@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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20230531151506.GO17675%40fattuba.com.

No comments:

Post a Comment