0

我正在一个 django 网站上工作,其中包含一个联系信息表格,我目前正在使用引导程序使其“看起来很漂亮”。我想使用 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')

类 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 %}

验证器.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'],
                    }
                }
            }     

        }
    });
});
4

1 回答 1

1

好的,我想通了,这真的很简单。我在 base.html 文件中包含了这个 javascript 作为结束 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 没有显示,但是当用户填写该字段时,验证消息正在显示,这是我真正需要的。希望其他人能找到这一点,这样他们就不必像我一样长时间地埋头苦干。

于 2014-08-04T21:20:18.733 回答