简体   繁体   中英

Client Side Validation not working in django.

**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})

First you must add this line after div tag.

   <script type = 'text/javascript' href="{% static 'validateForm.js' %}" >

I advice you create blockjs and add your js file here

Please , read this for more info

https://docs.djangoproject.com/en/1.10/ref/templates/language/#template-inheritance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM