如何仅从django modelform获取电子邮件提交的文本字段数据?我在视图中尝试了很多变化,cleaning_data.get()def clean(self):方法等。不确定为什么这么难。
# models.py - service model
class Service(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
service_type = models.ManyToManyField('ServiceType')
description = models.TextField(blank=True)
def __str__(self):
return "Service Order for: {user}".format(user=self.user)
class ServiceType(models.Model):
label = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.label
# forms.py
class NewServiceForm(forms.ModelForm):
accept_tos = forms.BooleanField(required=True)
class Meta:
model = Service
fields = '__all__'
exclude = ('user', 'created_at',)
# views.py
@login_required
def newservice(request):
if request.method == 'POST':
form = NewServiceForm(request.POST)
if form.is_valid():
form.instance.user = request.user
service = form.save()
# SEND EMAIL - send copy of project/service modelform data to user and site owner
name = request.user.first_name+request.user.last_name
username = request.user.username
subject = 'New Service Order'
from_email = request.user.email
service_data = form.cleaned_data
message = ''' From: {} {} {}
\n {}
\n {}
'''.format(name, from_email, username, subject, service_data)
recipients = ['mytestemail@gmail.com', request.user.email]
try:
send_mail(subject, message, from_email, recipients)
except BadHeaderError:
return HttpResponse('Invalid header found.')
# END EMAIL
messages.warning(request, 'Success! Your service order has been submitted.')
return redirect('projects')
else:
messages.error(request, 'Invalid submission, check and try again.')
else:
form = NewServiceForm()
return render(request, 'dashboard/newservice.html', {'form': form})
# newservice.html
<form method="post" id="newprojectform">
{% csrf_token %}
Service Type <br> {{ form.service_type }} <br><br>
{{ form.accept_tos }} <br><br>
Description {{ form.description }} <br><br>
<button class="btn btn-sm" type="submit">Submit</button>
</div>
</form>
我收到错误的输出发送到我的电子邮件收件箱下面:我只想要选择文本输出,并将描述发送到我的电子邮件收件箱(而不是布尔值= True),即&#39;编辑内容添加内容测试说明到这里& #39;
{'service_type': <QuerySet [<ServiceType: Edit Content>, <ServiceType: Add Content>, 'accept_tos': True, 'description': 'Test Description goes here'}
答案 0 :(得分:0)
在m2m表单字段数据检索出现很多问题之后,我使用project = form.save()对象从创建的模型中提取数据。很多冲突,但更容易解决。