Python 如何将InMemoryUploadedFile放入文件字段?
上下文:Python 如何将InMemoryUploadedFile放入文件字段?,python,python-3.x,django,Python,Python 3.x,Django,上下文: pip冻结: asgiref==3.2.10 dist==1.0.3 Django==3.1.2 PyMySQL==0.10.1 pytz==2020.1 sqlparse==0.4.1 python--version: Python 3.6.7 email.html: <form action="" method="post" enctype="multipart/form-data"> {% cs
pip冻结
:
asgiref==3.2.10
dist==1.0.3
Django==3.1.2
PyMySQL==0.10.1
pytz==2020.1
sqlparse==0.4.1
python--version:
Python 3.6.7
email.html
:
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ recipient_form.as_p }}
{{ body_form.as_p }}
{{ attachments_form.as_p }}
<input type="submit" value="Submit">
</form>
views.py
:
def index(request, email_id=None):
context = {
'bucket': settings.BUCKET_URL, # where files are stored
'recipient_form': RecipientForm(prefix='recipient'),
'body_form': BodyForm(prefix="body"),
'attachments_form': AttachmentForm(prefix='attachments')
}
if email_id is not None and Email.objects.filter(pk=email_id).exists():
email = Email.objects.get(pk=email_id)
if request.method == 'POST':
recipient_form = RecipientForm(request.POST, prefix='recipient')
body_form = BodyForm(request.POST, prefix='body')
attachments_form = AttachmentForm(request.FILES, prefix='attachments')
if recipient_form.is_valid() and body_form.is_valid() and attachments_form.is_valid():
# here is where things got messy..
recipient = recipient_form
recipient.email = email
recipient.save()
body = body_form
body.email = email
body.save()
attachments = attachments_form
attachments.email = email
attachments.save()
return render(request, 'email.html', context)
forms.py
urlpatterns = [
path('email/<int:email_id>', email.index, name='email')
]
# ...
class AttachmentForm(ModelForm):
class Meta
model = Attachment
fields = ['file']
# ...
#...
def attachment_handler(instance, filename):
upload_to = 'attachments'
return os.path.join(upload_to, filename)
class Attachment(models.Model):
email = models.ForeignKey(Email, on_delete=models.CASCADE)
file = models.FileField(upload_to=attachment_handler, null=True, blank=True)
datestamp = models.DateTimeField(auto_now_add=True, null=True)
#...
models.py
urlpatterns = [
path('email/<int:email_id>', email.index, name='email')
]
# ...
class AttachmentForm(ModelForm):
class Meta
model = Attachment
fields = ['file']
# ...
#...
def attachment_handler(instance, filename):
upload_to = 'attachments'
return os.path.join(upload_to, filename)
class Attachment(models.Model):
email = models.ForeignKey(Email, on_delete=models.CASCADE)
file = models.FileField(upload_to=attachment_handler, null=True, blank=True)
datestamp = models.DateTimeField(auto_now_add=True, null=True)
#...
目标:
最好通过ModelForm
上传文件字段中的多个文件。如果不可能,每个附件只能有一个
到目前为止:
我可以通过ModelForm
上传一个没有错误的文件,但它不会像Django的内置admin
面板中所示那样持续存在。我可以对ImageField
执行相同的操作,但我需要FileField
才能工作
问题似乎在于将文件上传到模型的FileField中,但我不知道为什么
打印(请求文件)
MultiValueDict:{'attachment-file':[]}>
尝试:
- 收益率:
“非类型”对象没有属性“文件”
- 收益率:
'MultiValueDict'对象没有属性“save”