**I am a newbie to Django and jQuery. I want client side validations in my django project. This simple project is uploading a file and displaying the contents. I am currently just checking that the file field is not empty but it is not working.
Moreover, I want to add the code to validate the file such that it can only upload .txt and image files as well as the maximum size of file must not exceed 500KB. How can I add these validations in my .js file?**
Template
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css'%}"/>
<script type = 'text/javascript' href="{% static 'validateForm.js' %}" >
</script>
<div class = "formArea">
<div class = "fileForm">
<form enctype="multipart/form-data" method="post"> {% csrf_token %}
<div class = "formFields">
<label for = "file"> {{ form.file.label }} </label>
{{ form.file }}
{{ form.file.errors }}
</div>
<div class = "formFields">
<input type="submit" value="Submit">
</div>
</form>
</div>
</div
validateForm.js
$(document).ready(function() {
$('#form').validate({
rules: {
file: {
required: true
}
},
messages: {
file: {
required: 'Please Upload a File!'
}
}
});
});
Form.py
from django import forms
class fileForm(forms.Form):
file = forms.FileField(label = 'Upload File' )
Views.py
from django.shortcuts import render_to_response, HttpResponse
from .forms import fileForm
def uploadFile(request):
if(request.method == 'POST'):
form = fileForm(request.POST, request.FILES)
if(form.is_valid()):
file = request.FILES['file']
fileName = file.name
# file.size returns file size in Bytes
fileSize = file.size
extension = fileName[fileName.index('.'):]
return HttpResponse(file, content_type='text/plain')
else:
form = fileForm()
return render_to_response('UploadForm.html', {'form': form})