我是使用django作为框架的新手,当我尝试在我的自定义control_panel上保存简报时遇到问题,我可以保存消息但网络崩溃并向我显示一个typeError告诉我类模型我制作'NewsletterUsuario',但只是在自定义control_panel上,在django管理模式下它正常工作,问题开始发生在我从我不想使用的应用程序中删除一些文件后,甚至我做了git重置为工作版本仍然得到这个类似的typeError,这里是我的模型,视图和回溯:
models.py
from django.db import models
# Create your models here.
class NewslettersUsuario(models.Model):
email = models.EmailField()
fecha_agregado = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
class Newsletter(models.Model):
EMAIL_STATUS_CHOICES = (
('Draft', 'Draft'),
('Published', 'Published')
)
subject = models.CharField(max_length =250)
body = models.TextField()
email = models.ManyToManyField(NewslettersUsuario)
status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
Views.py
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render
from django.core.mail import send_mail, EmailMultiAlternatives
from django.template.loader import get_template
from .models import NewslettersUsuario, Newsletter
from .forms import NewslettersUsuarioSignUpForm, NewsletterCreacionForm
# Create your views here.
def newsletter_signup(request):
form = NewslettersUsuarioSignUpForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
if NewslettersUsuario.objects.filter(email=instance.email).exists():
messages.warning(request,
"Lo siento! este Correo ya existe.",
'alert alert-warning alert-dismissible')
else:
instance.save()
messages.success(request,
"Tu e-mail a sido agregado!",
'alert alert-success alert-dismissible')
subject = "Gracias por uniter a nuestro Newsletter"
from_email = settings.EMAIL_HOST_USER
to_email = [instance.email]
with open(settings.BASE_DIR + "/templates/newsletters/sign_up_email.txt")as f:
signup_message = f.read()
message = EmailMultiAlternatives(subject=subject, body=signup_message, from_email=from_email, to=to_email)
html_template = get_template("newsletters/sign_up_email.html").render()
message.attach_alternative(html_template, "text/html")
message.send()
context = {
'form':form,
}
template = 'newsletters/sign_up.html'
return render(request, template, context)
def newsletter_unsubscribe(request):
form = NewslettersUsuarioSignUpForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
if NewslettersUsuario.objects.filter(email=instance.email).exists():
NewslettersUsuario.objects.filter(email=instance.email).delete()
messages.success(request,
"Tu e-mail a sido eliminado.",
"alert alert-success alert-dismissible")
subject = "Haz sido dado de baja de nuestro Newsletter"
from_email = settings.EMAIL_HOST_USER
to_email = [instance.email]
with open(settings.BASE_DIR + "/templates/newsletters/unsubscribe_email.txt")as f:
signup_message = f.read()
message = EmailMultiAlternatives(subject=subject, body=signup_message, from_email=from_email, to=to_email)
html_template = get_template("newsletters/unsubscribe_email.html").render()
message.attach_alternative(html_template, "text/html")
message.send()
else:
messages.warning(request,
"Lo siento pero no encontramos tu Correo.",
"alert alert-warning alert-dismissible")
context = {
'form' : form,
}
template ='newsletters/unsubscribe.html'
return render(request, template, context)
这是追溯
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/control/newsletter/
Django Version: 2.0.1
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'whitenoise.runserver_nostatic',
'crispy_forms',
'newsletters',
'tutoriales']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\ASUS\Desktop\Downloadudacity\Workplace 2\pjt_cook\env\src\newsletters\views.py" in control_newsletter
80. send_mail(subject=subject, from_email=from_email, recipient_list=[email], message= body,fail_silently=True)
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\__init__.py" in send_mail
60. return mail.send()
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\message.py" in send
294. return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\backends\smtp.py" in send_messages
110. sent = self._send(message)
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\backends\smtp.py" in _send
123. recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()]
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\backends\smtp.py" in <listcomp>
123. recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()]
File "C:\Users\ASUS\Desktop\DOWNLO~1\WORKPL~2\pjt_cook\env\lib\site-packages\django\core\mail\message.py" in sanitize_address
103. addr = parseaddr(addr)
File "c:\users\asus\appdata\local\programs\python\python36-32\Lib\email\utils.py" in parseaddr
224. addrs = _AddressList(addr).addresslist
File "c:\users\asus\appdata\local\programs\python\python36-32\Lib\email\_parseaddr.py" in __init__
500. self.addresslist = self.getaddrlist()
File "c:\users\asus\appdata\local\programs\python\python36-32\Lib\email\_parseaddr.py" in getaddrlist
252. while self.pos < len(self.field):
Exception Type: TypeError at /control/newsletter/
Exception Value: object of type 'NewslettersUsuario' has no len()
希望你能帮助我理解为什么会这样做并找到解决方案,非常感谢你。
答案 0 :(得分:0)
问题在于代码:
for email in newsletter.email.all():
send_mail(subject=subject, from_email=from_email, recipient_list=[email], message= body,fail_silently=True)
在循环中,每个email
都是类NewslettersUsuario
的实例,而不是文本中的电子邮件地址。可能你需要email.email
:
for email in newsletter.email.all():
send_mail(subject=subject, from_email=from_email, recipient_list=[email.email], message= body,fail_silently=True)