django.core.exceptions.FieldError: 'pub_date' cannot be specified for Article model form as it is a non-editable field

created at 07-17-2021 views: 1

Introduction

In django development, an error is prompted when using django form:

  File "D:\software\python3.6\lib\site-packages\django\forms\models.py", line 256, in __new__
    apply_limit_choices_to=False,
  File "D:\software\python3.6\lib\site-packages\django\forms\models.py", line 149, in fields_for_model
    f.name, model.__name__)
django.core.exceptions.FieldError: 'pub_date' cannot be specified for Article model form as it is a non-editable fiel

model.py

class Article(TimeModel):

    title = models.CharField(max_length=150, verbose_name='article title')
    writer = models.CharField(max_length=20, verbose_name='author')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, db_index=True, verbose_name='category')
    arc_type = models.SmallIntegerField(default=0, choices=TYPE, verbose_name='article type')
    sort_rank = models.SmallIntegerField(default=0, db_index=True, verbose_name='sort rank')
    status = models.SmallIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, db_index=True, verbose_name='status')
    pub_date = models.DateTimeField(auto_now_add=True, verbose_name='created at')

After reading an article, I found that if DateTimeField is set to auto_now_add=True, even if editable=True is set, modification is not supported by default.

note:

The options auto_now_add, auto_now and default are mutually exclusive. Any combination of these options will cause an error.

In the current implementation, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True settings.

Solution

class Article(TimeModel):

    title = models.CharField(max_length=150, verbose_name='article title')
    writer = models.CharField(max_length=20, verbose_name='author')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, db_index=True, verbose_name='category')
    arc_type = models.SmallIntegerField(default=0, choices=TYPE, verbose_name='article type')
    sort_rank = models.SmallIntegerField(default=0, db_index=True, verbose_name='sort rank')
    status = models.SmallIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, db_index=True, verbose_name='status')
    pub_date = models.DateTimeField(verbose_name='created at')
Please log in to leave a comment.