0

I am working on a django website which includes a form for contact information and I am currently using bootstrap to make it "look pretty". I want to use bootstrapvalidator http://bootstrapvalidator.com/ to make the form easy to use for my users. I have heavily researched using django and bootstrapvalidator together and have found several different plugins or other ways to validate information entered into a form but they only give errors after the form is submitted, and what I want is live validation that shows the user appropriate messages as they type.

My biggest problem has been figuring out how/where to call the Javascript. I think the correct way to do this is by using a widget in the form, but nothing I have tried has done the job. Currently my page is displaying "emailval(parent_or_guardian_email)" where the email field should be.

Would anyone be able to tell me what I'm doing wrong or how to get my desired result? This is my first time using django or python at all.

relevant parts of my 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)

in my base.html I have the appropriate file imports

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

the html file for the page with the form

    {% 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 Answers1

1

Ok, I figured it out, it was really quite simple. I included this javascript as the last thing before the closing html tag in my base.html file:

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

above which (in base.html) I made sure to include the correct files (order does matter)

<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">    

and made my html for the page containing the form look like this

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

and I didn't need to create a widget outside the form, just include it like this

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)

for some reason the feedbackIcons aren't showing, but the validation messages are displaying as the user fills in the field, which is what I really needed. Hope someone else finds this so they don't have to bag their head for as long as I did.

  • Just a side note: you might want to use which is more readable and easier to maintain, and STATIC_URL is pre-defined in settings.py – Paul Lo Aug 25 '14 at 10:18