0
// signals.py

@receiver(pre_save, sender=AcademicLesson)
def take_attendance(sender, instance, **kwargs):
    new_file = instance.class_img
    if new_file:
        sub = instance.sub_id
       
        # this for loops gives all student from each branch having comman subject(sub = instance.sub_id)
        for branch in sub.universitybranch_set.all():
            for std in branch.studentprofile_set.all():
                if std.profile_encode: # for understanding, student present or not
                    print('-------------------------added')
                    instance.student.add(std)
                else:
                    print('---------------------not-added')
        print('no. of student=', len(instance.student.all()))
# // models.py

class AcademicLesson(models.Model):

    date = models.DateField()
    sub_id = models.ForeignKey('UniversitySubject', on_delete=models.CASCADE, limit_choices_to={'is_elect': True})
    class_type = models.CharField(max_length=7, choices=[('lecture','Lecture'),('lab','Lab')])
    slot = models.CharField(max_length=1, choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6')])
    class_img = models.ImageField(upload_to=path_to_upload_media, blank=True)
    student = models.ManyToManyField('StudentProfile', blank=True)

    def __str__(self):
        return f"{self.date} | {self.sub_id}"
    class Meta: 
        verbose_name = 'Academic Lesson'

form which I submited from admin panel

debug console look like

whene I verify with django shell, it return <QuerySet []>

lesson = AcademicLesson.objects.get(date='2021-04-05')
lesson.student.all()

what I tried.

  1. override models.Model.save method but same problem occurs.
  2. forms.ModelForm does not suitable for our project

If I run code shown in signals.py in django shell then it work properly but, same logic does not work in signals.py

where did I go wrong?

  • In order to save data in the m2m relation, first the object is saved, and *then* the relation is populated, this is necessary since before saving the `AcademicLesson` to the database, it has no primary key, and thus can not be linked to students. – Willem Van Onsem Apr 05 '21 at 19:42
  • thanks, for m2m relation is not necessary to save instance because instance.pk(or instance.id) contains the primary key which will save in database. however, I tried as per your suggestion but remain same problem. I change `pre_save` to `post_save` and `instance.student.add(std)` to `sender.objects.get(id=instance.id).student.add(std)` – Meet Patel Apr 06 '21 at 00:39

0 Answers0