Django中如何从User模型获取旅行发布者的用户邮箱?
解决从用户数据库获取旅行发布者邮箱的问题
核心逻辑是你的Post模型应该关联了发布旅行的用户(一般通过ForeignKey关联Django内置的User模型),所以可以直接通过当前获取的Post对象拿到关联用户的邮箱。
步骤1:确认Post模型的关联字段
假设你的Post模型定义类似这样(外键字段可能叫author/user/publisher,以下以author为例):
from django.db import models from django.contrib.auth.models import User class Post(models.Model): # 其他旅行相关字段(比如标题、行程等) title = models.CharField(max_length=200) # 关联发布者用户 author = models.ForeignKey(User, on_delete=models.CASCADE)
步骤2:修改视图代码获取邮箱
把你代码中userEmail = I need to assign email id of this trip posted user这一行替换成:
userEmail = context["data"].author.email
如果你的外键字段不是author,改成对应的名称即可(比如context["data"].user.email)。
修正其他潜在问题
你的代码里还有两个小问题需要调整:
send_mail函数的参数错误,最后一个desc是多余的,不符合函数签名- 邮件内容有语法错误,建议修正
修改后的完整视图代码:
def PostDetailView(request, pk): context = {} context["data"] = Post.objects.get(id=pk) if request.method == "POST": name = request.POST['uName'] # phone = request.POST["phone"] email = request.POST['uEmail'] desc = request.POST['uDes'] # 获取旅行发布者的邮箱 userEmail = context["data"].author.email subject = "I'm Interested in your Trip" # 修正邮件内容语法,优化可读性 message = f"Hi, I'm {name}. I'm interested in your trip. Please share more details with me at {email}.\nAdditional information: {desc}" email_from = email recipient_list = [userEmail, ] # 移除多余的desc参数 send_mail(subject, message, email_from, recipient_list) messages.success(request, 'Message Sent Successfully.') return render(request, 'ads/detail.html', context) return render(request, 'ads/detail.html', context)
额外优化建议
为了避免发布者没有邮箱导致报错,可以增加一个判断:
post_author = context["data"].author if not post_author.email: messages.error(request, 'This trip publisher has no email address on file, cannot send message.') return render(request, 'ads/detail.html', context) userEmail = post_author.email
内容的提问来源于stack exchange,提问作者Mrsreez
相关产品推荐
相关产品推荐

