Why filelist is empty even after uploading images - django

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">

Related

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'

Django: Image Upload to the Server

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

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?

problem handling upload file django

I'm trying to do a feature that would allow the user to upload a file. That file would have information to insert into the database, that's why in the function I'm saving data. Not sure if it's the best option.
What I've done so far:
forms.py:
class UploadFileForm(forms.Form):
file = forms.FileField()
views:
def last_step(request, word):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
msg = handle_uploaded_file(word, request.FILES['file'])
return render_to_response('final_insert.html', {'msg': msg})
else:
form = UploadFileForm()
return render_to_response('upload.html',
{
'word': word,
'form': form })
template:
<form enctype="multipart/form-data" action="{% url upload_done 'clinical' %}" method="post">
<div>
{% for field in form %}
{{ field }}
{% endfor %}
<input type="submit" value="Save" />
</div>
</form>
function:
def handle_uploaded_file(word, f):
msg = "first stop"
data = []
for chunk in f.chunks():
data.append(chunk)
msg = "after chunk"
if word == 'clinical':
pat = Patient.objects.values_list('patient', flat=True)
for i in data:
if i[0] not in pat:
b2 = Patient(patient=i[0])
b2.save()
msg = "number was inserted"
else:
msg = "something"
return msg
The problem is when I hit "save" in the template, it redirects well to another template, but I don't see any message, like I suppose to see (final_insert.html shows {{ msg }})
Can someone help me understand what I'm doing wrong?
Any help is welcome!
Thanks for your help!
I was able to understand my mistake.
sorry guys for my silly mistake
so this is the form:
<form enctype="multipart/form-data" action="{% url upload_done 'clinical' %}" method="post">
<div>
{% for field in form %}
{{ field }}
{% endfor %}
<input type="submit" value="Save" />
</div>
</form>
urls:
url(r'^insert/file/(?P<word>clinical)/upload/$', last_step, name="upload"),
url(r'^insert/file/(?P<word>clinical)/upload/result/$', final, name='upload_done'),
so the view last_step corresponds to the url "upload" and not "upload_done"
I wrote into the form action={% url upload_done 'clinical' %}, so when I hit save it will redirect me automatically to the other template. Without running the code!!
So I changed the form to:
<form enctype="multipart/form-data" action="{% url upload 'clinical' %}" method="post">
<div>
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<input type="submit" value="Guardar" />
</div>
</form>
and now it works..
sorry guys, I thought I needed to redirect to the other page but when he redirects he doesn't run the code..