Django two forms on the same page - django

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'

Related

Django Return redirect working for one view but not for the other

I cannot understand why it is working in one instance but not the other. I am working with django and output in django template. The only difference between the views/functions are in the second one (the one that is not working) I update the field with time. Time updates, saves in the model and displays updated time correctly. It is just the redirect that is not working.
The working redirect code-
Template, this code takes me to the edit page. Name of the url is "update" -
<td><button>Edit</button></td>
The form on the dit page-
{% block content %}
<div class="wrapper">
<h1 class="ok">Entry Form</h1>
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="submit">
</form>
</div>
<br>
{% endblock content %}
url-
path('update_entry/<str:pk>/', views.update, name = "update"),
And views.py-
def update(request, pk):
order=Bank1.objects.get(id=pk)
form = Bank1Form(instance=order)
if request.method == 'POST':
form = Bank1Form(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/bank1')
context = {'form':form}
return render(request, 'myapp/entry.html', context)
Now here is the non working code. Template, the line that takes me to the update page. Name of the url is "update_enter_workout.-
<td><button>Start Time</button></td>
Form on the Edit page. Didn't add the entire form since I only need to update the time from this page. Just the submit button.-
{% block content %}
<Button>Close this page and go to Home</Button>
<div class="wrapper">
<h1 class="ok">Start/End the set now?</h1>
<form action="" method="post">
{% csrf_token %}
<input type="submit" value="YES!">
</form>
</div>
{% endblock content %}
url-
path('update_enter_workout/<str:pk>/', views.update_workout, name='update_enter_workout'),
Views.py-
def update_workout(request, pk):
order=WorkOut.objects.get(id=pk)
form=WorkOutForm(instance=order)
if request.method=='POST':
form=WorkOutForm(request.POST, instance=order)
time=datetime.now().strftime('%H:%M:%S')
WorkOut.objects.filter(id=pk).update(start=time)
if form.is_valid():
form.save()
return redirect('/bank1')
context={'form':form}
return render(request, 'myapp/enter_workout.html', context)
As you can see they are written the same way, but in the second instance redirect is not working. Any idea what can be changed. It is so simple, couldn't even find a typo or simple mistake like that.
Any advise?
Are you accepting str for id fields? Primary Keys are integers, not strings. You need to cast to an int path converter:
Instead of:
path('update_enter_workout/<str:pk>/', views.update_workout, name='update_enter_workout'),
Use:
path('update_enter_workout/<int:pk>/', views.update_workout, name='update_enter_workout'),

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

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

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)