使用Django创建或更新实例时通过电子邮件发送

时间:2018-11-05 15:50:29

标签: django python-3.x django-rest-framework django-email django-rest-viewsets

简介:我有2个Django Rest Framework模型PatientEmbryo,只有1个用户是超级用户。所有患者都属于超级用户。一个病人可以有很多埃布罗氏病,但是每个胚胎只能有一个病人。

我想做什么:我正在尝试在创建或更新患者模型或胚胎模型时向患者发送电子邮件。下面是我的代码我在做什么错

以下是我的观点。py

 def send_email_confirmation(instance):
    patient = Patient.objects.get(id=instance)
    embryo = Embryo.objects.filter(patient=patient)
    try:
        '''Sending the Order to the patient'''
        subject = "Gemonic Prediction Create or Update record"
        to = ['{}'.format(patient.email)]
        from_email = "no_reply@genomicprediction.com/"
        order_information = {
            'patient': patient,
            'embryo': embryo
        }
        message = get_template('email/email.html').render(order_information)
        msg = EmailMessage(subject, message, to=to, from_email=from_email)
        msg.content_subtype = 'html'
        msg.send()
    except IOError as e:
        return e


class PatientsApiView(viewsets.ModelViewSet):
    """Handles Creating, reading and updating Patients"""

    serializer_class = serializers.PatientsSerializer
    queryset = Patient.objects.all()
    authentication_classes = (TokenAuthentication,)
    filter_backends = (filters.SearchFilter,)
    permission_classes = (IsAuthenticated,)
    search_fields = ("first_name", "last_name", "phone", "email",)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
        instance = serializer.save()
        try:
            send_email_confirmation(created=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

    def perform_update(self, serializer):
        instance = serializer.save()
        try:
            send_email_confirmation(modified=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e


class EmbroApiView(viewsets.ModelViewSet):
    """Handles Creating, reading and updating Patients"""

    serializer_class = serializers.EmbryoSerializer
    queryset = Embryo.objects.all()
    authentication_classes = (TokenAuthentication,)
    filter_backends = (filters.SearchFilter,)
    permission_classes = (IsAuthenticated,)
    search_fields = ("code_name", "karyotype", "sex", "down_syndrome",)

    def perform_create(self, serializer):
        serializer.save(pk=self.kwargs.get("pk"))
        instance = serializer.save()
        try:
            send_email_confirmation(created=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

    def perform_update(self, serializer):
        instance = serializer.save()
        try:
            send_email_confirmation(modified=instance)
            print('An email has been sent to the customer.')
        except IOError as e:
            return e

我的模型在下面,以防万一

class Patient(models.Model):
    """Patients model which has all the patients information"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=25)
    last_name = models.CharField(max_length=35)
    phone = models.CharField(max_length=18)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def __str__(self):
        return "%s %s" % (self.full_name, self.email)


class Embryo(models.Model):
    """A ForeignKey model to the patient"""
    patient = models.ForeignKey(Patient, related_name="embryos", on_delete=models.CASCADE)
    code_name = models.CharField(max_length=100)
    karyotype = models.CharField(max_length=100)
    down_syndrome = models.BooleanField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    GENDER_CHOICES = (
        ("M", "Male"),
        ("F", "Female"),

    )
    sex = models.CharField(blank=True, null=True, max_length=1, choices=GENDER_CHOICES)

2 个答案:

答案 0 :(得分:1)

您可以使用Django的信号。

在模型更改时会发出信号。这是官方文档https://docs.djangoproject.com/en/2.1/topics/signals/

答案 1 :(得分:0)

在类EmbroApiView中,方法perform_updateperform_createsend_email_confirmation的实例调用Patient(在序列化器上调用save的结果) 。在函数send_email_confirmation中,第一行是

patient = Patient.objects.get(id=instance)

因此,您使用Patient的实例作为id,这是我看到的第一个错误。

第二个类似,但是在这种情况下,使用类EmbroApiView时,您要使用send_email_confirmation实例调用方法Embryo