从外键查询数据(特别是UserProfile)

时间:2013-01-17 20:05:25

标签: django django-views

如果我的模型包含一些继承自UserProfile模型的字段:

class LeaveRequest(models.Model):
    employee = models.ForeignKey(UserProfile)
    supervisor = models.ForeignKey(UserProfile, related_name='+', blank=False, null=False)
    submit_date = models.DateField(("submit date"), default=datetime.date.today)
    leave_type = models.CharField(max_length=64, choices=TYPE_CHOICES)
    start_date = models.DateField(("start date"))
    return_date = models.DateField(("return date"))
    ...

我使用此模型创建模型表单:

class LeaveRequestForm(ModelForm):
    class Meta: 
        model = LeaveRequest

如何查询用户个人资料中的电子邮件网址?在此视图功能中,我正在尝试将表单提交的通知电子邮件发送给发件人(员工)和主管:

def create_request(request):
    if request.method == 'POST':
        form = LeaveRequestForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['employee']
            subject = form.cleaned_data['leave_type']
            message = form.cleaned_data['notes']
            sender = form.cleaned_data['employee']

            remoterq = form.save(commit=False)
            remoterq.save()
            form.save_m2m()
            recipients = [user.email for user in remoterq.employee, user.email for user in remoterq.supervisor]
            from django.core.mail import send_mail
            send_mail(subject, message, 'projects.xxx@google.com', recipients, fail_silently=False)
            return HttpResponseRedirect('.')

我的“收件人”var的代码无效,但我不知道如何修复它。

1 个答案:

答案 0 :(得分:0)

尝试

remoterq.employee.user.email

用于员工电子邮件和

remoterq.supervisor.user.email

主管电子邮件。