【发布时间】:2015-02-22 22:13:03
【问题描述】:
我是 Django 新手。我的 html 文件中有以下代码:
{% load staticfiles %}
<form method="post"> {% csrf_token %}
<input type="file" name="file">
<button>Submit</button>
</form>
{{file}}
<img class="hl" src="{{ MEDIA_URL }}photos/abc.png" /></a>
<img class="hl" src="{% static 'blog/images/sec.png' %}" /></a>
上面代码的views.py是:
if request.method == 'POST':
if 'file' in request.POST:
f = request.POST['file']
a = MyUser(email="frt@wer.com", date_of_birth=date.today())
a.photo.save('somename.png', File(open(f, 'r')))
a.save()
context = {'file': f}
return render(request, 'home.html', context)
现在浏览器不会从用户的本地设备返回文件的绝对路径,它只是收集文件名,因为security issues 但a.photo.save('somename.png', File(open(f, 'r'))) 我的这部分代码需要用户本地设备的绝对路径,类似于@987654327 @我得到的只是sec.png,因此我无法上传。
来自python manage.py shell:
>>>a = MyUser(email="frt@wer.com", date_of_birth=date.today())
>>>a.photo.save('somename.png', File(open('/home/abc/Pictures/sec.png', 'r')))
>>>a.save()
这很好用。是否有一些解决方法。我不想使用Form。
【问题讨论】:
标签: python django django-file-upload django-media