Reputation: 33
In this class when I add post I want to call category_change when the category field changes.
How can I do that?
class Post(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey('Category', on_delete=models.CASCADE,null=True,blank=True,)
image = models.ImageField(default='default.jpg', null=True, blank=True,editable=False)
series = models.ForeignKey('Series', on_delete=models.CASCADE,null=True,blank=True,editable=False)
tags = models.ManyToManyField('FilmTags', related_name='post')
content = models.TextField()
watch = models.TextField(null=True, default='')
download_url = models.CharField(max_length=300, null=True, default="#")
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
publish = models.BooleanField(default=True)
views = models.IntegerField(default=0)
def category_change(self):
if category.title == "series":
self.image.editable = True
self.series.editable = True
self.image = self.series.image
else:
self.image.editable = True
Upvotes: 2
Views: 728
Reputation: 7717
Django signals is what you need. Signals will notify you instance changed, is something like database trigger. Demo is here:
signals.py:
from django.db.models.signals import post_save
from django.dispatch import receiver
from .model import Post
@receiver(post_save, sender=Post)
def is_category_changed(sender, instance=None, created=False, **kwargs):
instance.category_change()
apps.py:
from django.apps import AppConfig
class PostConfig(AppConfig):
name = 'Post'
verbose_name = 'Post'
def ready(self):
import post.signals # post is your app name
Upvotes: 2
Reputation: 1
You need to build up the services you were into again so you can recovered you're in formation again
cmodels.TextField(null=True)
Upvotes: 0
Reputation: 881
You can add a method of creation , which takes the fields that you want to fill as arguments and create an instance , the method category_change()
will be run withing this declaration
class Post(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey('Category',
on_delete=models.CASCADE,null=True,blank=True,editable=False)
...
def createPost(self,arg1,arg2,...) :
post = self(title=arg1,category=arg2...)
category_change()
return post
# here is how you can call it
post = Post.createPost(title,category,...)
Upvotes: 0