我需要为Django 1.8应用程序添加一个简单的消息传递功能。我有Message
模型和以下Attachment
模型:
class Attachment(models.Model):
message = models.ForeignKey(Message)
file = models.FileField()
用户应该可以使用此formset创建包含多个附件的邮件:
AttachmentFormset = inlineformset_factory(Message, Attachment, extra=1, exclude=[], can_delete=False)
这就是我的模板中所有表单的呈现方式:
<form action="" method="post">
{% csrf_token %}
{{ msg_form.as_p }}
{{ attachment_formset.management_form }}
{% for form in attachment_formset.forms %}
{{ form.as_p }}
{% endfor %}
<input class="button" type="submit" value="{% trans 'Send'%}"></input>
</form>
这是我在视图中处理表单的方式:
if request.method == "POST":
msg_form = MessageForm(request.POST)
attachment_formset = AttachmentFormset(request.POST, request.FILES)
sender = request.user
if msg_form.is_valid() and attachment_formset.is_valid():
msg = msg_form.save(sender=sender)
for aform in attachment_formset:
a = aform.save(commit=False)
a.message = msg
a.save()
问题在于,request.FILES
总是空的,附件表单的cleaned_data
也是空的。上传的文件发生了什么变化?!使用FileField
处理内联formset的正确方法是什么?
答案 0 :(得分:1)
您的表单缺少enctype
<form action="" method="post" enctype="multipart/form-data">