从视图集中将模型对象传递给函数

时间:2019-04-15 21:14:47

标签: django email serializer

我有一个Django视图集,其中有一个函数,只要使用该视图集,它就会发送一封电子邮件。

我重写了create函数,以发送电子邮件,而我有一个函数,可以将电子邮件发送给用户。

我想将一些参数传递给函数,以在电子邮件中显示(使用Django的模板引擎完成)

class ContactRequestViewSet(viewsets.ModelViewSet):
queryset = ContactRequest.objects.all()
permission_classes = [
    permissions.AllowAny
]
serializer_class = ContactRequestSerializer

def create(self, request, *args, **kwargs):
    response = super(ContactRequestViewSet, self).create(request, *args, **kwargs)
    send_email()
    return response

#function to send email
def send_email():
htmly = get_template('email.html')
d = {'company_name': 'dodo'} #i want this dictionary, to contain the attributes from the viewset
send_mail(
    subject='Test email',
    message='',
    from_email='test@email.com',
    recipient_list=['test@email.com'],
    html_message= htmly.render(d)
)

现在我只有一个示例占位符,为d,但在这里我想从用户提供的序列化器/模型中传递属性,我尝试传递序列化器并访问其属性,但是我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

您可以在此行之后访问response.data

response = super(ContactRequestViewSet, self).create(request, *args, **kwargs)

将保存序列化器的数据。但是,如果您想要模型的实际实例,这还远远不够,那么您将需要一点点尝试。 django-rest-framework的CreateModelMixin中使用的ModelViewSet具有以下方法:

class CreateModelMixin:
    # ... more stuff here

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

因此您可以覆盖perform_create方法,以将实例保存到ContactRequestViewSet的属性中,如下所示:

def perform_create(self, serializer):
    self.instance = serializer.save()

然后在create方法中,您可以执行以下操作:

def create(self, request, *args, **kwargs):
    response = super(ContactRequestViewSet, self).create(request, *args, **kwargs)  # This calls perform_create internally
    send_email(self.instance)
    return response