如何在Django中实现bootstrap验证

时间:2014-08-01 17:37:53

标签: python django twitter-bootstrap jqbootstrapvalidation

我正在开发一个django网站,其中包含一个联系信息表单,我目前正在使用bootstrap使其“看起来很漂亮”。我想使用bootstrapvalidator http://bootstrapvalidator.com/使表单易于用户使用。我已经大量研究过使用django和bootstrapvalidator并找到了几种不同的插件或其他方法来验证输入到表单中的信息但是它们只在提交表单后给出错误,而我想要的是实时验证,它将用户显示的相应消息作为他们打字。

我最大的问题是弄清楚如何/在哪里调用Javascript。我认为正确的方法是在表单中使用一个小部件,但我尝试过的任何东西都没有完成这项工作。目前我的页面显示“emailval(parent_or_guardian_email)”,其中应包含电子邮件字段。

有人能告诉我我做错了什么或如何得到我想要的结果?这是我第一次使用django或python。

我的models.py的相关部分

from django.db import models as db_models
from django.db import models
from django.contrib.auth.models import User
from django import forms
from django.contrib.admin import widgets
from django.forms import extras
import datetime
from django.core.validators import *
from django.forms import ModelForm
from django.contrib import admin

import logging

class EmailWidget(forms.TextInput):
    def render(self, name, value, attrs=None):
        out = super(EmailWidget,self).render(name, value, attrs=attrs)
        return out + '<script type="text/javascript">emailval(parent_or_guardian_email)            </script>'

class Media:
    js = ('../validator.js')

class PersonForm(forms.Form):

    ready_to_play = forms.BooleanField(initial = True )       
    first_name = forms.CharField(max_length=35)
    last_name = forms.CharField(max_length=35)
    phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
    grade = forms.IntegerField(initial = 99, required = False)
    age = forms.IntegerField(initial = 99, required = False)
    gender = forms.ChoiceField(choices=GENDERS, required = False)
    sport = forms.ChoiceField(choices=SPORTS, required = False)

    #fields for parent_or_guardian and physician not autofilled
    parent_or_guardian = forms.CharField(max_length=35, required = False)
    parent_or_guardian_phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
    parent_or_guardian_email = forms.EmailField(widget =EmailWidget(),help_text = "Changing this field will create a new user for this email address, if you wish to change this user's contact information"
    +" please ask them to do so on their page or contact a site admin ")

    physician = forms.CharField(max_length=35, required = False)
    physician_phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
    #Pphone = copy.deepcopy(physician.phone)
    #Pphone =str(physician_phone)
    #physician_phone = re.sub('.','-',str(Pphone))
    physician_email = forms.EmailField(max_length=75, required = False)

在我的base.html中我有相应的文件导入     

<link href ="../../../../static/spotlight/assets/css/bootstrap-responsive.css" rel="stylesheet">
<link href ="../../../../static/spotlight/assets/css/bootstrapValidator.min.css" rel="stylesheet">
<script src="../../../../../static/spotlight/assets/js/jquery-1.11.1.min.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap-tab.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap.min.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap-formhelpers.min.js"></script>
<script type="text/javascript" src="../../../../static/spotlight/assets/js/bootstrapValidator.min.js"></script>

表格为

的页面的html文件
    {% extends "spotlight/base.html" %}

{% block content %}
<h3>Update {{ athlete }}</h3>
<br>
<form class="form-horizonal" role="form" action="{% url 'spotlight:athleteedit' athlete.id %}" method="post" id="PersonForm">
    {% for field in form %}
            <div class="form-group"><p>

                {{ field.label_tag }}&nbsp;{{ field }}
                {% for error in field.errors %}
                    &nbsp;<font color="Red">{{ error }}</font>&nbsp; 
                {% endfor %}
            </p></div>
        {% endfor %}
{% csrf_token %}

<input class="btn btn-default" type="submit" value="Submit" />
</form>


{% endblock content %}

validators.js

 $(document).ready(function emailval() {
    $('#PersonForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {

            parent_or_guardian_email: {
                validators: {
                    emailAddress: {
                        message: 'The value is not a valid email address'
                        excluded: [':disabled'],
                    }
                }
            }     

        }
    });
});

1 个答案:

答案 0 :(得分:1)

好的,我想通了,这真的很简单。我将这个javascript包含在我的base.html文件中关闭html标记之前的最后一件事:

    <body>

<script type="text/javascript">
$(document).ready(function() {
    $('#PersonForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {

            parent_or_guardian_email: {
                validators: {
                    notEmpty: {
                        message: 'The email address is required and can\'t be empty'
                    },
                    emailAddress: {
                        message: 'The input is not a valid email address'
                    }
                }
            },

        }
    });
});
</script>
</body>

以上(在base.html中)我确保包含正确的文件(顺序很重要)

<link href ="../../../../static/spotlight/assets/css/bootstrap-responsive.css" rel="stylesheet">
    <link href ="../../../../static/spotlight/assets/css/bootstrap.css" rel="stylesheet">
    <link href ="../../../../static/spotlight/assets/css/bootstrapValidator.min.css" rel="stylesheet">    

并使包含表单的页面的html看起来像这样

 {% extends "spotlight/base.html" %}

{% block content %}
<h3> Add Athlete</h3>
<br>
<form  class="form-horizonal" role="form" action="{% url 'spotlight:addstu' person_id team_id %}" method="post" >
    {% for field in form %}
            <div class="fieldWrapper"><p>
                {% if field.label = "Parent or guardian email" %}

                            <div class="col-lg-5" id="PersonForm">
                            {{ field.label_tag }}&nbsp;{{ field }}
                            </div>

                {% else %}
                {{ field.label_tag }}&nbsp;{{ field }}
                {% for error in field.errors %}
                    &nbsp;<font color="Red">{{ error }}</font>&nbsp; 
                {% endfor %}
                {% endif %}
            </p></div>
        {% endfor %}
{% csrf_token %}

<input class="btn btn-default" type="submit" value="add athlete" /> 
</form>
{% endblock content %}

我不需要在表单外创建一个小部件,只需像这样包含它

parent_or_guardian_email = forms.EmailField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control','name':"parent_or_guardian_email",'class':"col-lg-5",}),help_text = "Changing this field will create a new user for this email address, if you wish to change this user's contact information"
        +" please ask them to do so on their page or contact a site admin ",max_length=75)

由于某种原因,feedbackIcons没有显示,但验证消息显示为用户填写字段,这是我真正需要的。希望别人能够发现这一点,这样他们就不必像我一样长时间掏腰包。