How to check value transition in Django (django-admin)? (Revisited)
I was wondering about 开发者_运维百科how to control transitions in model data. I found the solution at How to check value transition in Django (django-admin)? but when I tried to implement it within my code, something went wrong (I am able to change the status with impunity):
Here is the relevant portion of my code:
# Blog Entry Draft Status Constants
ENTRY_STATUS_DRAFT = 0
ENTRY_STATUS_PUBLISHED = 1
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=200, unique=True)
body_html = models.TextField(blank=True)
pub_date = models.DateTimeField ('Date Published', blank=True, null=True, editable=False)
PUB_STATUS = (
(ENTRY_STATUS_DRAFT, 'Draft'),
(ENTRY_STATUS_PUBLISHED, 'Published'),
)
status = models.IntegerField(choices=PUB_STATUS, default=0)
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError('Draft entries may not have a publication date.')
# Set the publication date for published items if it hasn't been set already
if self.status == ENTRY_STATUS_PUBLISHED and not self.pub_date:
self.pub_date = datetime.datetime.now()
def clean_status(self):
status = self.cleaned_data.get('status')
if status == ENTRY_STATUS_DRAFT:
if self.instance and self.instance.status == ENTRY_STATUS_PUBLISHED:
raise ValidationError('You cannot change published to draft')
return status
The clean() method works. I also tried using 'Published' and 'Draft' in the clean_status() method but that didn't work.
Am I putting clean_status in the right place? Am I overlooking something?
Your clean method should return the self.cleaned_data
just like the clean_status
returns the self.cleaned_data['status']
. :)
精彩评论