我想向所有教授与新问题相关科目的教师发送一封电子邮件(无论是由管理面板还是问题创建表单创建的(,以便他们可以批准该问题。如何做到这一点?
型号.py
class Usuario(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,verbose_name="Usuário")
USUARIO_CHOICES = (
(UM,'Aluno'),
(DOIS,'Professor'),
)
tipoUsuario = models.IntegerField('Tipo de Usuário',choices=USUARIO_CHOICES,default=1)
class Questao(models.Model):
aOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra a")
bOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra b")
cOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra c")
dOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra d")
eOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra e")
设置.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail@outlook.com'
EMAIL_HOST_PASSWORD = 'Mypassword'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'MySite <myemail@outlook.com>'
views.py
def add_questoes(request):
if request.method == 'POST': # If the form has been submitted...
form = QuestaoForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
subject = 'Questão adicionada'
message = 'Há uma nova questão adicionada'
recepient = str(sub['Email'].value())
send_mail(subject,
message, EMAIL_HOST_USER, [recepient], fail_silently = False)
return redirect('/') # Redirect after POST
else:
form = QuestaoForm() # An unbound form
return render(request, 'polls/add_question.html', {'form': form})
forms.py
class QuestaoForm(forms.ModelForm):
aOpcao = forms.CharField(max_length=500,label="Letra a")
bOpcao = forms.CharField(max_length=500,label="Letra b")
cOpcao= forms.CharField(max_length=500,label="Letra c")
dOpcao = forms.CharField(max_length=500,label="Letra d")
eOpcao = forms.CharField(max_length=500,label="Letra e")
class Meta:
model = Questao
fields = '__all__'
看看这个文档:
https://docs.djangoproject.com/en/2.2/ref/signals/
Django后保存信号是在特定的DB操作后执行代码的好方法。在你的情况下,我认为你需要创建一个postrongave信号来触发电子邮件的发送。