客户端验证无法在django中运行。

时间:2017-03-16 07:06:09

标签: jquery django validation client-side

**我是Django和jQuery的新手。我想在我的django项目中进行客户端验证。这个简单的项目是上传文件并显示内容。我目前只是检查文件字段是否为空但它不起作用。

此外,我想添加代码来验证文件,使其只能上传.txt和图像文件以及文件的最大大小不得超过500KB。如何在我的.js文件中添加这些验证?**

模板



{% 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
   
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:0)

首先,您必须在div标签后添加此行。

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

我建议你创建blockjs并在这里添加你的js文件

请阅读此内容以获取更多信息

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