提交表单后如何发送电子邮件[Django-rest-framework]

时间:2019-01-04 09:14:26

标签: django django-rest-framework

我制作了一个用于在我的应用程序中提交联系表的api。 每当提交表单时,我都希望它通过电子邮件将详细信息发送给自己。 这是我正在使用的代码:

models.py

class Contact(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=254)
    phone = models.CharField(max_length=20)
    message = models.TextField()

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'contact'

views.py

from rest_framework.generics import (
    CreateAPIView,
)
from .serializers import (
    ContactCreateSerializer
)
class ContactCreateApiView(CreateAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactCreateSerializer

serializers.py

class ContactCreateSerializer(ModelSerializer):
class Meta:
    model = Contact
    fields = [
        'name',
        'email',
        'phone',
        'message',
    ]

def send_email(self):
    name = self.cleaned_data.get('name')
    from_email = self.cleaned_data.get('email')
    phone = self.cleaned_data.get('phone')
    subject = 'Contact Form Info from App'
    message = self.cleaned_data.get('message')
    to_email = settings.EMAIL_HOST_USER

    context = {
        'name': name,
        'email': from_email,
        'phone': phone,
        'message': message,
    }
    plaintext = get_template('emails/contact_form_email.txt')
    htmly = get_template('emails/contact_form_email.html')
    text_content = plaintext.render(context)
    html_content = htmly.render(context)

    message = EmailMultiAlternatives(
        subject=subject, 
        body=text_content, 
        from_email=from_email, 
        to=[to_email],
        cc=[],
        bcc=[]    
    )
    message.attach_alternative(html_content, "text/html")
    message.send()

def save(self, commit=True):
    instance = super().save(commit)
    self.send_email()  # there you send the email when then model is saved in db
    return instance

我尝试了这个,但是给了我错误

save() takes 1 positional argument but 2 were given

我该怎么办?

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。其中之一是覆盖ModelSerializer的create方法:

from django.core.mail import send_mail


class ContactCreateSerializer(ModelSerializer):
    class Meta:
        model = ContactForm
        fields = [
            'name',
            'email',
            'phone',
            'message',
        ]

     def create(self, validate_data):
        instance = super(ContactCreateSerializer, self).create(validate_data)
        send_mail(
            'Instance {} has been created'.format(instance.pk),
            'Here is the message. DATA: {}'.format(validate_data),
            'from@example.com',
            ['to@example.com'],
            fail_silently=False,
        )
        return instance

有关发送电子邮件的更多详细信息,请检查此documentation

仅供参考:请将您的型号名称从ContactForm更改为Contact。因为它是模型,而不是形式。老实说。您不需要存储联系信息。您可以这样做:

class ContactSerailizer(Serializer):
   name = serializers.CharField()
   email = serializers.EmailField()
   # and so on

Class ContactView(APIView):
    def post(self, request, *args, **kwargs):
         serailizer = ContactSerailizer(request.data)
         if serailizer.is_valid():
             data = serailizer.validated_data
             email = validated_data.get('email')
             name = validated_data.get('name')
             send_mail(
                'Sent email from {}'.format(name),
                'Here is the message. {}'.format(validate_data.get('message')),
                email,
                ['to@example.com'],
                fail_silently=False,
            )
            return Response({"success": "Sent"})
         return Response({'success': "Failed"}, status=status.HTTP_400_BAD_REQUEST)