Domanda

In a Mezzanine project, I have defined a simple Photo model that extends the core Page model:

from django.db import models
from mezzanine.pages.models import Page

class Photo(Page):
    image = models.ImageField(upload_to="photos")
    #publish_date = models.DateTimeField(auto_now_add=True, blank=True) #problematic

When I tried to re-define the publish_date field, I got error:

django.core.exceptions.FieldError: Local field 'publish_date' in class 'Photo' clashes with field of similar name from base class 'Page'

I want to avoid filling publish_date in admin page each time I create a photo. So wondering how should I set it it to now() without touching the original Page model?

È stato utile?

Soluzione

You can't change the definition of a field in a derived class of a model -- what if the base class relies on the existing behavior in any way?

What I'd suggest is define a custom save() method in your Photo class that adds the date, then calls the super() save:

import datetime
def save(self, *args, **kwargs):
    if not self.pk:
        # instance is being created.
        self.publish_date = datetime.datetime.now()
    super(Photo, self).save(*args, **kwargs)

If you find yourself doing this a lot, you could create a mixin that adds this functionality to any class.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top