здесь я хочу создать ярлык на основе содержимого автоматически непосредственно перед сохранением экземпляра модели вопроса, но поле slug не создается, поскольку я хочу, чтобы вот мои models.py
class Question(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
content = models.CharField(max_length=240)
slug = models.SlugField(max_length=240, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="questions")
class Answer(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
body = models.TextField()
question = models.ForeignKey(Question,
on_delete=models.CASCADE,
related_name="answers")
author = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
voters = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name="votes")
мои приложения .py
from django.apps import AppConfig
class QuestionsConfig(AppConfig):
name = 'questions'
def ready(self):
import questions.signals
my init .py
default_app_config = "questions.apps.QuestionsConfig"
и, наконец, signal.py
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.text import slugify #we'll use it to create slug based on the content of the instance
from core.utils import generate_random_string
from questions.models import Question
@receiver(pre_save, sender=Question)
def add_slug_to_question(sender,instance,**kwargs):
if instance and not instance.slug:
slug = slugify(instance.content)
random_string = generate_random_string()
instance.slug = slug + "-" + random_string