2

I am new to Django.I have the following code on my html file:

{% 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>

and my views.py for the above code is:

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)

Now browsers do not return the absolute path of the file from user's local device, it just gathers filename because ofsome security issues but a.photo.save('somename.png', File(open(f, 'r'))) this part of my code needs absolute path of user local device that is something like /home/abc/Pictures/sec.png all i get is sec.png and hence i am unable to upload.

From 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()

This works fine. Is there some workaround. I dont want to use Form.

4

1 回答 1

2

我建议如果您想允许文件上传,请使用文件表单而不是解决方法。可以在这里找到一个简单且非常简洁的示例:

需要一个最小的 Django 文件上传示例

于 2014-12-24T23:28:23.737 回答