- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试在表单中创建 FileField,并且不在本地保存文件,而是将文件(作为附件)添加到电子邮件中并发送。代码的电子邮件部分工作正常,但是当我添加 FileField 时,它显示错误“'str'对象没有属性'get'”,我正在努力找出问题所在。
查看:
def print(request):
if request.method == 'POST':
form = PrintForm(data=request.POST, request = request)
#print(request.FILES)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
form_content = request.POST.get('content', '')
supervisor = form.cleaned_data['supervisor']
template = get_template('threeD/email/contact_template_for_printing.txt')
context = Context({
'contact_name': contact_name,
'supervisor': supervisor,
'contact_email': contact_email,
'form_content': form_content,
})
content = template.render(context)
subject = "New message"
try:
email = EmailMessage(
subject,
content,
contact_email,
[supervisor],
headers={'Reply-To': contact_email}
)
if request.FILES:
#uploaded_file = request.POST.get('file')
uploaded_file = request.FILES['stl_file'] # file is the name value which you have provided in form for file field
email.attach('uploaded_file.name, uploaded_file.read(), uploaded_file.content_type')
email.send()
except:
return "Attachment error"
messages.success(request, "Thank you for your message.")
return redirect('/index/print/')
else:
form = PrintForm(request=request)
context_dict = {}
context_dict['printers'] = Printer.objects.all()
context_dict['form'] = form
return render(request, 'threeD/print.html', context_dict)
表格:
class PrintForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
supervisor = forms.ChoiceField(
choices=[(str(sup.email), str(sup.name)) for sup in Supervisors.objects.all()]
)
stl_file = forms.FileField(required=False)
stl_file.help_text = "Upload your file as .STL format. If you have more than one file, " \
"make a .zip and upload them all at once"
content = forms.CharField(
required=True,
widget=forms.Textarea
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(PrintForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
self.fields['stl_file'].label = "Choose your design file:"
这是 HTML 代码片段,我在其中调用表单:
<div class="panel-body">
<form role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% load bootstrap %}
{{ form|bootstrap }}
<div class="text-center">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-send"></span>
Send a message
</button>
</div>
</form>
</div>
环境:
Request Method: POST
Request URL: http://localhost:8000/index/print/
Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'threeD.apps.ThreedConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrapform',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
这就是我遇到的错误:
Traceback:
File "C:\Python34\lib\site-packages\django-1.9-py3.4.egg\django\core\handlers\base.py" in get_response
235. response = middleware_method(request, response)
File "C:\Python34\lib\site-packages\django-1.9-py3.4.egg\django\middleware\clickjacking.py" in process_response
31. if response.get('X-Frame-Options') is not None:
Exception Type: AttributeError at /index/print/
Exception Value: 'str' object has no attribute 'get'
从 View 中删除 try- except 情况后,我得到以下回溯:回溯:
File "C:\Python34\lib\site-packages\django-1.9-py3.4.egg\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django-1.9-py3.4.egg\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Python\Facility\threeD\views.py" in print
145. email.attach('uploaded_file.name, uploaded_file.read(), uploaded_file.content_type')
File "C:\Python34\lib\site-packages\django-1.9-py3.4.egg\django\core\mail\message.py" in attach
307. assert content is not None
Exception Type: AssertionError at /index/print/
Exception Value:
任何帮助将不胜感激。谢谢!
最佳答案
看起来点击劫持中间件正在爆炸,因为它读取的响应是一个字符串,而它应该是其他内容。
查看您的代码,这一行可能是罪魁祸首返回“附件错误”
尝试将其更改为
返回 HttpResponse('附件错误')
你可以像这样导入HttpResponse from django.http import HttpResponse
关于python - 文件字段在 Django 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464373/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!