Django сигнализирует данные по умолчанию, работающие для одного ребенка, но не для многих - PullRequest
0 голосов
/ 04 апреля 2020

У меня есть файл сигналов, который я хотел бы запускать каждый раз, когда создается ребенок. По какой-то причине он создал информацию по умолчанию для одного дочернего элемента, но если добавлен другой, он не создает информацию по умолчанию. Также не работает для других пользователей, по какой-то причине работал только для моей учетной записи.

signal.py файл:

from django.db.models.signals import post_save
from django.dispatch import receiver
from children.models import Children
from .models import Timeline

@receiver(post_save, sender=Children)
def init_new_child(instance, created, raw, **kwargs):
    # raw is set when model is created from loaddata.
    if created and not raw:
        Timeline.objects.create(header = "Financial Support", age = "0-4",children=instance)
        Timeline.objects.create(header = "Financial Support", age = "4-11",children=instance)
        Timeline.objects.create(header = "Financial Support", age = "11-18",children=instance)
        Timeline.objects.create(header = "Financial Support", age = "18-25",children=instance)

        Timeline.objects.create(header = "Educational Support", age = "0-4",children=instance)
        Timeline.objects.create(header = "Educational Support", age = "4-11",children=instance)
        Timeline.objects.create(header = "Educational Support", age = "11-18",children=instance)
        Timeline.objects.create(header = "Educational Support", age = "18-25",children=instance)

        Timeline.objects.create(header = "Governmental Support", age = "0-4",children=instance)
        Timeline.objects.create(header = "Governmental Support", age = "4-11",children=instance)
        Timeline.objects.create(header = "Governmental Support", age = "11-18",children=instance)
        Timeline.objects.create(header = "Governmental Support", age = "18-25",children=instance)

        Timeline.objects.create(header = "Charity Support Groups", age = "0-4",children=instance)
        Timeline.objects.create(header = "Charity Support Groups", age = "4-11",children=instance)
        Timeline.objects.create(header = "Charity Support Groups", age = "11-18",children=instance)
        Timeline.objects.create(header = "Charity Support Groups", age = "18-25",children=instance)

        Timeline.objects.create(header = "Therapy Support", age = "0-4",children=instance)
        Timeline.objects.create(header = "Therapy Support", age = "4-11",children=instance)
        Timeline.objects.create(header = "Therapy Support", age = "11-18",children=instance)
        Timeline.objects.create(header = "Therapy Support", age = "18-25",children=instance)

        Timeline.objects.create(header = "Transport Support", age = "0-4",children=instance)
        Timeline.objects.create(header = "Transport Support", age = "4-11",children=instance)
        Timeline.objects.create(header = "Transport Support", age = "11-18",children=instance)
        Timeline.objects.create(header = "Transport Support", age = "18-25",children=instance)

Детская модель:

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.urls import reverse



DIAGNOSIS_CHOICES = [
        (1, ("Yes")), 
        (2, ("No"))
]

class Children(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    age = models.CharField(max_length=100)
    diagnosis = models.IntegerField(
        choices= DIAGNOSIS_CHOICES,
    )
    disability = models.CharField(max_length=100)
    parent = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name + " " + self.last_name

    def get_absolute_url(self):
        return reverse('children-detail', kwargs={'pk': self.pk})*

Модель времени:

from django.db import models
from django.contrib.auth.models import User
from posts.models import PDF
from children.models import Children

HEADER_CHOICES = [
    ('Financial Support', 'Financial Support'),
    ('Educational Support', 'Educational Support'),
    ('Governmental Support', 'Governmental Support '),
    ('Charity Support Groups', 'Charity Support Groups'),
    ('Therapy Support', 'Therapy Support '),
    ('Transport Support', 'Transport Support ')
]
AGE_CHOICES = [
    ('0-4', '0-4'),
    ('4-11', '4-11'),
    ('11-18', '11-18'),
    ('18-25', '18-25')
]

class Timeline(models.Model):
    header = models.CharField(max_length=30, choices=HEADER_CHOICES)
    age = models.CharField(max_length=6, choices=AGE_CHOICES)
    child = models.OneToOneField(Children, on_delete=models.CASCADE)

class Pdf(models.Model):
    pdf = models.FileField(upload_to='timelinepdfs')
    timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE)

1 Ответ

1 голос
/ 07 апреля 2020

Из Django документации :

Обратите внимание, что функция принимает аргумент отправителя вместе с аргументами с подстановочными словами (** kwargs); все обработчики сигналов должны принимать эти аргументы.

Таким образом, документация Django не является явной, является ли отправитель аргументом ключевого слова или позиционным аргументом. Из последнего кода 2.2 видно, что это ключевое слово arg, но я проверил только одну версию. Вы можете попробовать добавить отправителя в качестве первого аргумента.

from children.models import Children
from .models import Timeline, HEADER_CHOICES, AGE_CHOICES

@receiver(post_save, sender=Children)
def init_new_child(sender, instance, created, raw, **kwargs):
    # raw is set when model is created from loaddata.
    if created and not raw:
        # Just a DRY suggestion:
        for header in HEADER_CHOICES:
            for age in AGE_CHOICES:
                Timeline.objects.create(
                    header=header[0],
                    age=age[0],
                    child=instance
                )
...