Reputation: 707
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="[email protected]", 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="[email protected]", 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
.
Upvotes: 2
Views: 1760
Reputation: 5074
I would suggest that if you want to allow for a file upload that you use a File form rather than a workaround. A simple and very succinct example can be found here:
Need a minimal Django file upload example
Upvotes: 2