1.前端必须加enctype="multipart/form-data"
例如:
<form action="{% url 'blog:album_add' %}" method="post" enctype="multipart/form-data" >
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="save"></p>
</form>
2.view.py
def post(self,request):
form = AblumForm(data = request.POST,files=request.FILES)
if form.is_valid():
cd = form.cleaned_data
new_album = form.save(commit=False)
new_album.user = request.user
new_album.save()
return HttpResponseRedirect(reverse("blog:album_list"))
else:
return HttpResponse("添加相册失败")
一开始一直写的是form = AblumForm( request.POST)
,form.cleaned_data
文件字段一直是None
,改成form = AblumForm(data = request.POST,files=request.FILES)
后就好了 。这个破问题搞了我一下午,无语了。