【问题标题】:Client Side Validation not working in django.客户端验证在 django 中不起作用。
【发布时间】:2017-08-07 05:34:36
【问题描述】:

**我是 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
   

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

【问题讨论】:

    标签: jquery django validation client-side


    【解决方案1】:

    首先你必须在 div 标签之后添加这一行。

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

    我建议你创建 blockjs 并在此处添加你的 js 文件

    请阅读本文了解更多信息

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

    【讨论】:

    • 有点了解您要提出的建议。 @mubariz 我刚刚安装了 jQuery 验证库(django-parsley)。现在它显示必填字段的默认错误消息。 “这是必填栏”。它没有显示我在 js 文件中添加的消息。
    • 对于更改错误消息,请尝试以下脚本:&lt;script&gt; jQuery.extend(jQuery.validator.messages, { required: "Please Upload a File!", }); &lt;/script&gt; P.S:如果问题已解决,请标记“此答案很有用”:)
    • 不可能:) 你在哪里写的?
    • $('#formFile').validate({ rules: { file: "required" }, }); 像这样编辑您的代码并将 id="formFile" 添加到
      所以:&lt;form id="formFile" enctype="multipart/form-data" method="post"&gt; {% csrf_token %}
    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2021-09-24
    • 2012-05-26
    相关资源
    最近更新 更多