2
votes

I created a model on django for blog posts. Each post has two status choices: Publish or Draft. How can i change Publish to Published after the post is saved?

This is my code:

from django.db import models

from django.contrib.auth.models import User

Create your models here.

STATUS = ( (0,"Draft"),

(1,"Publish"), )

class Post(models.Model):

title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.Integer(choices=STATUS, default=0)
class Meta:
        ordering = ['-created_on']

def __str__(self):
        return self.title

from django.contrib import admin from .models import *

Register your models here

class PostAdmin(admin.ModelAdmin):

list_display = ('title','slug','status','created_on',)

list_filter  = ("status",)

search_fields = ('title', 'content')

prepopulated_fields = {'slug': ('title',)}

admin.site.register(Post,PostAdmin)

1

1 Answers

1
votes

Your first way is to change your value "publish" just to "published". There's no point of having additional "publish" status. Whenever a post is saved the status field should change to "published". If anyways you need it to be there,then you can add another BooleanField like "is_published" to your model and check it in your save method so whenever the self.status was equal to "publish", make the field True. If you want to have additional checks for your model; then just write a function for your model class to change the value of "is_published".

so to change the value of "is_published" field in model;

in your Post class: add

is_published = models.BooleanField(default=False)

then override your model save method:

def save(self, *args, **kwargs):
    if self.status == 1:
        self.is_published = True
    super(Post, self).save(*args, **kwargs)