Django Rest Framework - DELETE ajax call failure due to incorrect CSFR token - ajax

I'm trying to use the django rest framework to to easily handle some models as restful resources.
this is the code that I have:
Django: 1.7.1
Django REST Framework: 2.4.4
jQuery: 2.1.1
# models.py
class DocumentNodeTemplate(MPTTModel):
"""
"""
document_template = models.ForeignKey(
DocumentTemplate,
related_name="nodes",
verbose_name="Document template"
)
parent = TreeForeignKey(
'self',
null=True, blank=True,
related_name='children'
)
section_template = models.ForeignKey(
'SectionTemplate',
related_name="node_templates",
verbose_name="Section template"
)
def __unicode__(self):
return self.section_template.name
def get_class(self):
type = self.section_template.type
return import_string(type)
# serializers.py
class DocumentNodeTemplateSerializer(serializers.ModelSerializer):
class Meta:
model = DocumentNodeTemplate
fields = ('document_template', 'parent', 'section_template')
# views.py
class DocumentNodeTemplateAPIView(CreateAPIView, RetrieveUpdateDestroyAPIView):
queryset = DocumentNodeTemplate.objects.all()
serializer_class = DocumentNodeTemplateSerializer
<!-- HTML (section - admin's change form customization)-->
<fieldset class="module aligned">
<h2>{{ node_fieldset_title }}</h2>
<div class="form-row document-nodes">
<div
style="width: 100%; min-height: 450px;" id="general-container"
data-document_model="{{ document_model }}"
>
<form id="changelist-form" action="" method="post" novalidate>{% csrf_token %}
<div id="tree-container">
<div id="tree"
data-url="{{ tree_json_url }}"
data-save_state="{{ app_label }}_{{ model_name }}"
data-auto_open="{{ tree_auto_open }}"
data-autoescape="{{ autoescape }}"
>
</div>
<div class="add-node">
<a href="/admin/document/{{ model_name }}/add/?_to_field=id&document_id={{ object_id }}" class="add-another"
onclick="return showCustomAddAnotherPopup(event, this);">
<img src="/sitestatic/admin/img/icon_addlink.gif" width="10" height="10"
alt="Add another node"> Add another node
</a>
</div>
<ul class='node-custom-menu'>
<li data-action="delete">Delete node</li>
</ul>
</div>
</form>
<div id="node-container">
<h3 id="node-name"></h3>
<br/>
<div id="node-content"></div>
</div>
</div>
</div>
</fieldset>
// javascript
var performCRUDaction = function(action, api_url, callback) {
var csfrtoken = $('input[name="csrfmiddlewaretoken"]').prop('value');
var _reloadNodeTree = function () {
window.nodeTree.tree('reload');
}
var _performAction = function () {
jQuery.ajax({
type: actionType,
url: api_url,
data: { 'csrfmiddlewaretoken': csfrtoken },
success: function () {
console.log("action " + action + " successfully performed on resource " + api_url);
_reloadNodeTree();
},
error: function () {
console.log("action " + action + " failed on resource " + api_url);
}
});
}
var actionType,
documentModel = null;
var nodeDataObj = {};
switch (action) {
case "delete":
actionType = "DELETE";
break;
case "update":
actionType = "PUT";
break;
case "create":
actionType = "POST";
break;
case "retrieve":
actionType = "GET";
break;
}
_performAction();
callback();
}
I didn't posted all the code, anyway when that ajax call is triggered, I obtain a 403 error:
// headers
Remote Address:127.0.0.1:8050
Request URL:http://127.0.0.1:8050/api/documentnodetemplates/46
Request Method:DELETE
Status Code:403 FORBIDDEN
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:djdt=hide; sessionid=x5cw6zfifdene2p7h0r0tbtpkaq7zshq; csrftoken=NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Host:127.0.0.1:8050
Origin:http://127.0.0.1:8050
Pragma:no-cache
Referer:http://127.0.0.1:8050/admin/document/documenttemplate/1/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
X-CSRFToken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
csrfmiddlewaretoken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Response Headersview source
Allow:GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type:application/json
Date:Thu, 20 Nov 2014 09:52:31 GMT
Server:WSGIServer/0.1 Python/2.7.6
Vary:Accept, Cookie
X-Frame-Options:SAMEORIGIN
// response
{"detail": "CSRF Failed: CSRF token missing or incorrect."}
Anybody experienced the same or similar problem and can help?
Thanks
LuKe

You should delete all your Cookies and other site and plug-in data and Cached images and files by going into history tab and then clear browsing data...ANother option is to use #csrf_exempt decorator with your class based views..

Related

Login form django using ajax

I have a login form of Django and i want to redirect user to the landing page if the password and the username is matching and to show an alert message if the login is failed and eventually show a validation error if the form is submitted empty.
When i submit the form using the right credentials the user is logged but no message is shown on the form, on the server log i have this message
09/May/2019 23:35:52] "POST /login/ HTTP/1.1" 200 7560
when i submit an empty form i have this message
Bad Request: /login/
[09/May/2019 23:36:53] "POST /login/ HTTP/1.1" 400 0
and when i submit a wrong credentials i have this message
[09/May/2019 23:37:36] "POST /login/ HTTP/1.1" 200 61
This is my html form
<div id="cd-login"> <!-- log in form -->
<div class="login_div"></div>
<form id="login_form" class="cd-form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<p class="fieldset">
<label class="image-replace cd-email" for="signin-email">E-mail</label>
<input class="full-width has-padding has-border" id="username" type="text" name="username" placeholder="E-mail">
<span class="cd-error-message">Error message here!</span>
</p>
<p class="fieldset">
<label class="image-replace cd-password" for="signin-password">Password</label>
<input class="full-width has-padding has-border" id="password" type="text" name="password" placeholder="Password">
Hide
<span class="cd-error-message">Error message here!</span>
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Login">
</p>
</form>
<p class="cd-form-bottom-message">Forgot your password?</p>
<!-- Close -->
</div> <!-- cd-login -->
This is my views.py
def ajax_login(request):
if request.method == 'POST':
username = request.POST.get('username', '').strip()
password = request.POST.get('password', '').strip()
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
# User is active
if user.is_active:
# Officially log the user in
return render(request, 'issueresolver/landing_page.html')
else:
data = {'success': False, 'error': 'User is not active'}
else:
data = {'success': False, 'error': 'Wrong username and/or password'}
return HttpResponse(json.dumps(data), content_type='application/json')
# Request method is not POST or one of username or password is missing
return HttpResponseBadRequest()
This my js file
$('form').on('submit', function(e) { e.preventDefault()
$.ajax({
type:"POST",
url: $(this).attr('action'),
data: $('#login_form').serialize(),
beforeSend: function (xhr, settings) {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(response){
/* here i am supposed to redirect user if login success and show an alert error message if the login is failed */
}
});
});
If any one can help me adjusting my code to be working as i described i will be more than grateful.
Finally i managed to solve the issue making some changes to the view.
This is the working code :
def ajax_login(request):
if request.method == 'POST':
username = request.POST.get('username', '').strip()
password = request.POST.get('password', '').strip()
response_data = {}
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
login(request, user)
response_data['result'] = 'Success!'
response_data['message'] = 'You"re logged in'
else:
response_data['result'] = 'Failed!'
response_data['message'] = 'Login Failed, Please check your credentials'
return HttpResponse(json.dumps(response_data), content_type="application/json")
return render(request, 'login.html')
ajax call
$('form').on('submit', function(e) { e.preventDefault()
$.ajax({
type:"POST",
url: $(this).attr('action'),
data: $('#login_form').serialize(),
beforeSend: function (xhr, settings) {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(response){
if (response['result'] == 'Success!')
window.location = '/';
else
alert(response['message']);
}
});
});

Django Ajax post 500 internal error

i hope you can help me, im trying to make a django post form without reloading the page using ajax, but im getting error 500 when submit, can you help me to fix this, this is my code:
models.py
class ProductoConcepto(models.Model):
producto = models.ForeignKey(Producto)
orden = models.ForeignKey(Cobro)
cantidad = models.FloatField()
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from cobro import views
urlpatterns = [
url(r'^cobro/agregar_concepto/$', views.addconcept_product, name='add_concepto'),
]
views.py
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('')
template
<div class="modal inmodal fade" id="myModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-m">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Cerrar</span>
</button>
<h3 class="modal-title">Agregar nuevo concepto</h3>
</div>
<div class="modal-body">
<p>Datos de concepto a agregar:</p>
<div class="doctorformstyle">
<form id='formulario-modal' method='post' enctype='multipart/form-data'>
{% csrf_token %}
<ul>{{form2.as_p}}</ul>
<!-- rendered form2 fields: <select id="id_producto" name="producto"><option value="1" selected="selected">object</option></select> -->
<!-- form2 fields: <select id="id_orden" name="orden">
<option value="1" selected="selected">object</option>
</select> -->
<!-- form2 fields: <input id="id_cantidad" name="cantidad" step="any" type="number"> -->
<div class="row align-center">
<input type='submit' name="save1" value='Guardar' class="btn btn-w-m btn-primary"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).on('submit', '#formulario-modal', function(e){
e.preventDefault();
$.ajax ({
type: 'POST',
url: '{% url 'add_concepto' %}',
data: {
producto: $('#id_producto').val(),
orden: $('#id_orden').val(),
cantidad: $('#id_cantidad').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
},
sucess:function(){
alert("OK");
}
})
});
</script>
this is the error: POST http://127.0.0.1:8000/cobro/agregar_concepto/ 500 (Internal Server Error)
I think that maybe something is missing in my view, buy i dont know that, cal you help me?
Edit: Traceback added
Environment:
Request Method: GET Request URL:
http://127.0.0.1:8000/cobro/agregar_concepto/
Django Version: 1.9.7 Python Version: 2.7.11 Installed Applications:
('django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles', 'entrada',
'cobro', 'catalogo', 'selectize', 'smart_selects') Installed
Middleware: ('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in
get_response
158. % (callback.module, view_name))
Exception Type: ValueError at /cobro/agregar_concepto/ Exception
Value: The view cobro.views.addconcept_product didn't return an
HttpResponse object. It returned None instead.
You view is not complete:
As the exception states: The view cobro.views.addconcept_product didn't return an proper HttpResponse object.
return HttpResponseRedirect('/thanks/')
Are you viewing the exception you provided in a new window? Because it is showing
"Request Method: GET" which shouldn't be happening via your ajax function.
Modify your view to this:
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('Product Created')
else:
return HttpResponse('Product Creation failed')
else:
return HttpResponse('Failed: Post requests only.')
Update your return statement with something like.
return HttpResponse('Product Created !')
Also as you are using ajax, you can also return a JsonResponse.
First import it
from django.http import JsonResponse
and then return your response
JsonResponse({'success': 'Product created'})
The exception is getting raised because you are not handling the condition if the method is not POST, and you are submitting a GET request.
Handle the cases for invalid form and if method is not POST.
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
....
return JsonResponse({'success': 'Product created'})
else:
return JsonResponse({'error': 'InValid Form.Product Creation Failed'})
else:
return JsonResponse({'error': 'Only POST method allowed'})
Also use ajax method attribute instead of type.
$.ajax ({
method: 'POST',
url: '{% url 'add_concepto' %}',
....
});

Django-registration ajax post form

registration and to make validations I will be submitting the form via Ajax.
I have checked other posts and tried some options, but the csrf_token gives a jscript error
Uncaught SyntaxError: Unexpected identifier
The form is for login, and if data is entered ok, the form submits ok even with the error. But if the entered data is wrong, just does nothing.
$(document).on("submit", this.id, function(e) {
e.preventDefault();
var frm = e.target.id;
var frmData = $("#"+frm).serialize();
$.ajax({
type: "POST",
url: '{% url 'django.contrib.auth.views.login' %}',
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
csrfmiddlewaretoken : '{% csrf_token %}',
data: frmData,
success: function(data)
{
console.log('success');
},
error: function (data) {
console.log('error');}
});
I also have the csrf_token tag in the form.
I think this will solve your problem:
// ajax components
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
And what my form looked like:
<ul class="sub-menu collapse" id="settings">
<form id="glucose_boundary_form" action="/glucose/goals" method="POST">
{% csrf_token %}
{{ glucose_boundary_form.as_p }}
</form>
<button type="submit" id="glucose_goals">Submit</button>
</ul>
What a button click looked like
$('button#glucose_submit').click(function() {
$.ajax({
url:'glucose/submit',
type: 'POST',
data: $('form#glucose_form').serialize(),
success: function(data) {
document.getElementById("glucose_form").reset();
}
});
});
EDIT:
Here is my login and registration view. Although I do not use ajax for registration. The form validation happens automatically for the login page. Hope they helps you see what I'm doing and how you might apply my answer.
from django import forms
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from loginregistration.models import loginForm, registrationForm
# Login user method
def login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('')
form = loginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
auth_login(request, user)
return HttpResponseRedirect('/') # Redirect to a success page.
return render(request, 'login.html', {'form': form})
# Logout user method
def logout(request):
auth_logout(request)
return HttpResponseRedirect(reverse('loginregistration.views.login')) # Redirect to a success page.
# Register user method
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'POST': # If the form has been submitted...
form = registrationForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
password = form.cleaned_data['password']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
# Tries to create a new user and add them to the database
try:
User.objects.create_user(username, email=email, password=password, first_name=first_name, last_name=last_name)
except:
#Add error
return HttpResponseRedirect('#ERROR')
return HttpResponseRedirect('/login') # Redirect after POST
else:
form = registrationForm() # An unbound form
return render(request, 'register.html', {'form': form})
Here is my login template:
{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block content %}
<form method="post" action="" id="login" class="container"
style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
{% csrf_token %}
<h1 style="text-align: center">Login to Your Account</h1>
<div class="form-group container" style="max-width: 300px;">
{{form.as_p}}
<button type="submit" class="btn btn-primary">Login</button>
Create an account
</div><br>
</form>
<script type="text/javascript">document.forms.login.id_username.focus();</script>
{% endblock %}
Here is my registration template:
{% extends "base.html" %}
{% block title %}Create Account{% endblock %}
{% block content %}
<form method="post" action="" id="register" class="container "
style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
{% csrf_token %}
<h1 style="text-align: center">Register for an Account</h1>
<b></b>
<p style="text-align: center">WARNING: This is a prototype website for testing purposes only. For security reasons, do not use your real credentials!</p>
<div class="form-group container" style="max-width: 300px;">
{{form.as_p}}
<button type="submit" class="btn btn-primary btn-block">Create The Account</button>
</div>
</form>
<script type="text/javascript">document.forms.register.id_firstName.focus();</script>
{% endblock %}

Upload data and image base 64 to rest server as truncated

I'm using advanced rest console of chrome and i'm sending a rest request to a server that saves an image to database.
below the header data and the body of the request:
Header:
Content-Type: image/jpg; charset=UTF-8
Body:
device_id=1442045686166&id_utente=1&id_attivita=-1&id_prodotto=115&file=/9j/4AAQSkZJRgABAQAAAQABAAD/...
the server, not mine, it all comes back ok but here is the result
image returned
The other images were uploaded from Android application that sends requests to the same server!
The server is a java web application deployed on jboss application server.
This is the html part of retrive image:
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<label for="exampleInputEmail1">Immagine</label>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="thumbnail">
<i ng-hide="imageSrc">Nessuna immagine selezionata</i>
<img ng-hide="!imageSrc" ng-src="{{imageSrc}}" on-error-src="images/noimg.png" spinner-on-load/>
<div class="caption">
<div class="form-group">
<input type="file" id="imageInputFile" name="imageInputFile" ng-model="imageInputFile" ng-change="uploadFile(this)" ng-file-select="onFileSelect($files)" base-sixty-four-input maxsize="500" accept="image/*">
<p class="help-block">Scegli un'immagine in locale.</p>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the angularjs code:
$scope.uploadImage = function (id_prodotto) {
trace("uploadImage, inizio");
var img64 = $scope.imageSrc.replace(/^data:image\/(png|jpeg);base64,/, "");
$scope.bodyRawImg =
'device_id=' + $scope.key +
'&id_utente=' + $scope.BeanUtente[0].id_utente +
'&id_attivita=' + $scope.BeanUtente[0].id_attivita +
'&id_prodotto=' + id_prodotto +
'&file=' + img64;
trace("uploadImage, $scope.bodyRawImg " + $scope.bodyRawImg);
$http({
method: 'POST',
url: ($location.absUrl().split("/easyMenu/"))[0] + '/app/file/uploadFoto',
async: false,
processData: false,
headers: {
'Content-Type': 'image/jpg'
},
data: $scope.bodyRawImg,
})
.success(function (data, status, headers, config) { // success
trace("uploadImage, success");
$scope.result = (data || []);
trace("uploadImage response: " + JSON.stringify($scope.result));
})
.error(function (data, status, headers, config) { // error
trace("uploadImage, error");
});
$scope.cambioImmagine = false;

Django Jquery Form no AJAX request

After reading other questions on similar subject, I still do not understand what's wrong with this code.
I am testing a code that uses Jquery Form plugin. I added a call in the view to the template, to display it for 1st time so user can select file and upload. But it never sends the AJAX request, hence the code section in view is not executed. Although not shown here, jQuery library and the jQueryForm plugin are indeed being called.
Template:
<form id="uploadForm" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
<script>
var message = '';
var options = {
type: "POST",
url: '/upload/file/',
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
$('#uploadForm').ajaxSubmit(options);
</script>
View:
def upload(request):
response_data = {}
if request.method == 'POST':
if request.is_ajax:
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload(
upload=request.FILES['upload']
)
upload.name = request.FILES['upload'].name
upload.save()
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded:"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "We're sorry, but kk something went wrong. Please be sure that your file respects the upload conditions."
return HttpResponse(json.dumps(response_data), content_type='application/json')
else:
form = UploaderForm()
return render(request, 'upload.html', {'form': form})
It does call template correctly during first time, it displays buttons, it executes the script again but the form is not valid, so response_data is with error.
What am I missing?
Thanks, Ricardo
You can try using the example from API section instead, just look at the source code:
$('#uploadForm').ajaxForm({
beforeSubmit: function(a,f,o) {
$('.upload-message').html('Submitting...');
},
success: function(data) {
$('.upload-message').html('Done!');
}
});
and the HTML:
<form id="uploadForm" action="/upload/file/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
File: <input type="file" name="file">
{{ form.docfile }}
<span class="upload-message"></span>
<input type="submit" value="Upload" />
</form>
How it is supposed to be worked if there are no form data send in your script.
var options = {
type: "POST",
url: '/upload/file/',
data: new FormData(document.getElementById('uploadForm')),
processData: false,
contentType: false,
error: function(response) {
message = '<span class="error">We\'re sorry, but something went wrong. Retry.</span>';
$('.upload-message').html(message);
$('fileInput').val('');
},
success: function(response) {
message = '<span class="' + response.status + '">' + response.result + '</span> ';
message = ( response.status == 'success' ) ? message + response.fileLink : message;
$('.upload-message').html(message);
$('fileInput').val('');
}
};
You have at least one problem with you view - this:
if not request.GET:
return render(request, 'upload.html')
will prevent further execution when request.GET is empty which is the case when doing a POST request.

Resources