Django: Image Upload to the Server - django

I want to upload the image to the server. for that I have created a form and within my views.py file I tried to submit it into the sever. Here it does not uploads the file to "images" folder. instead of that it only update the database filed with new image name. So can anyone give me a solution.
this is views.py file
#login_required
def edit_profile(request):
if request.POST:
employee = Employee.objects.get(user=request.user)
employee.avatar=request.POST.get('image')
employee.save()
return HttpResponseRedirect('/view_profile/')
user_profile = request.user.get_profile()
return render_to_response('edit_profile.html',{'profile':user_profile },context_instance=RequestContext(request))
here my html code
{% block content %}
<form action="." method="post">
{% csrf_token %}
<input type="file" name="image"/>
<input type="submit" value="Save Changes" name="save" />
</form>
{% endblock %}
what should i change to upload image to the "images" folder

You need to add enctype="multipart/form-data" in your form element, so that files are also uploaded and available in request.FILES in the view..
So update it to
<form action="." method="post" enctype="multipart/form-data" >
....
More info at Binding uploaded files to a form
To save the image its easier to use ModelForm and set image file appropriately. But still you want to save the object directly do
...
employee.avatar = request.FILES['image']
employee.save()
Ref File Uploads

Related

Why filelist is empty even after uploading images

I am trying to upload multiple images of a model(say ChannelPostImages) to django view.But when i'm using request.FILES.getlist it's empty.
<form method="POST" id="uploadimages" action="/Channels/SMusic/ChannelAdminPost/34/">
{% csrf_token %}
<input id="imager" type="file" name="Images"accept="image/*" multiple="True">
<button class="submitter">POST</button>
</form>
while my view function is as follows:-
def ChannelAdminPoster(request,channelname,userid):
if request.user.is_authenticated:
files = request.FILES.getlist('Images')
print(files)
for f in files:
print(f)
objec=get_object_or_404(channel,ChName=channelname)
else:
return redirect('home')
It should be printing path of images on command prompt.But it is showing an empty query.
You are missing enctype="multipart/form-data" .
<form method="POST" id="uploadimages" action="/Channels/SMusic/ChannelAdminPost/34/" enctype="multipart/form-data">

Django two forms on the same page

I have two forms on the same page.
The first form uses a 3rd party lib to upload a file to s3 and then preview what it just uploaded without changing state/ going to a different page.
The second form is going to save the url of the uploaded file to my model
However, when I submit the second form - the first form throws an error. About not having the required field (it thinks it is supposed to submit another file).
HTML
<form
id="s3form"
name="s3form"
action="{% url 'file_create' employee.uid %}"
method="post"
>
{% csrf_token %}
{{ form }}
</form>
<hr/>
<form
id="save-pic"
name="save-pic"
action="{% url 'employee_update_profile_pic' employee.uid %}"
method="post"
>
{% csrf_token %}
{# jquery inserts hidden input for image link after s3 upload #}
<input
id="save-pic-submit"
name="save-pic-submit"
type="submit"
value="Save"
>
</form>
UPDATE:
urls.py
path('employee/update/<str:uid>/profile-picture', views.file_create, name='file_create'),
path('employee/update/<str:uid>/profile-picture', views.employee_update_profile_pic, name='employee_update_profile_pic'),
views.py
def file_create(request, uid):
employee = Employee.nodes.get(uid=uid)
form = S3UploadForm(request.POST or None)
# this is not getting run... maybe because form intercepted by package?
if form.is_valid():
form.save()
messages.success(request, '''Successfully uploaded new profile pic! Lookin' good''')
return redirect("employee_detail", employee.uid)
return render(request, 'profile-picture.html', {'form': form, 'employee': employee})
def employee_update_profile_pic (request):
pdb.set_trace()
SOLVED: it was because they were sharing the same URL despite both being 'post'

Jquery File Upload plugin in django

I am trying to use jQuery file upload plugin to upload files
I am having a form containing text field and other inputs as well as the fileupload plugin specified file input as below
<form method="post" action="{% url 'compose' %}" id="fileupload" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="t1"/>
<input data-bfi-disabled='' multiple='' name='files[]' type='file'>
<input type="submit">
</form>
Then in Django view I am trying to access the files uploaded with the following
attachment = request.FILES.getlist("files[]")
But on submit clicking I am getting blank filelist.
Where am I doing wrong?
I dont need ajax submission of individual files.
I need to submit all files upload along with other input contents to the view.
UPDATE:
when I checked in the UI by removing css classes of file upload button i could see "No FILE CHOSEN" but I could see list of files like below
I am confused how to use this plugin to submit my form with the selected files and other fields
Why don't you use a Form models:
class FileUploadForm(forms.Form):
file_source = forms.FileField()
Then:
<form action="/upload/" method="post" id="file-upload-form" enctype="multipart/form-data"> {% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary" id='upload-btn'>Upload</button>
And your view:
def upload_view(request):
if request.is_ajax():
form = FileUploadForm(request.POST)
if form.is_valid():
print 'valid form'

ImageField doesn't upload

I have been trying to implement a image upload for changing avatar for individual users. The problem I have right now is that it never uploads to the folder. It works from the admin but it doesn't work on the template I've created
views.py
if 'avatar_upload' in request.POST:
avatar_form = UserAvatarForm(request.POST, request.FILES, instance=request.user.get_profile())
if avatar_form.is_valid():
avatar_form.save()
return HttpResponse(request.POST['avatar'])
return HttpResponse("Failed")
I've changed the code for viewing the outputs. I get the file name in the POST. But I don't have anything in the request.FILES. So I'm guessing it is a problem there, and I haven't found out so far what the problem could be. Or could it be some problem elsewhere?
template*
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for item in avatar_form %}<p>{{ item.label }}: {{ item }}</p>
{% endfor %}
<input type="submit" value="Upload avatar" name="avatar_upload">
</form>
Have you set enctype="multipart/form-data" in form in the template?

Another CRSF token error while uploading file in django

I'm trying to upload a csv file in my view. I included csrf token however I'm directly taking 403 error when I try to upload a file. Here is my view and template:
MY FORM HTML
<div class="file-boxes">
<form enctype="multipart/form-data" action="" encoding="multipart/form-data" id="upload-csv" method="post">
{% csrf_token %}
{{form.csv}}
<!-- <input class="input-file" id="fileInput" type="file" size="14" name="csv_upload" onchange="this.form.submit()"> -->
</form>
</div>
MY FORM
class DeliveryDataForm(forms.Form):
csv = forms.FileField(widget=forms.ClearableFileInput(attrs={'size:':14,'onchange':'this.form.submit()'}))
MY VIEW
def upload_data(request):
...
form = DeliveryDataForm()
if request.method == "POST":
import pdb
pdb.stack_trace()
form = DeliveryDataForm(request.POST, request.FILES)
return HttpResponse('asd')
return render_to_response(template,context)
I know there are some missing parts in the view but the strange thing is, it never enters the if part. Any idea ?
from django.shortcuts import render
# ...
# return render_to_response(template,context)
return render(request,'index.html',context)