Как реализовать начальную проверку в Django

Я работаю над сайтом 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')

Класс PersonForm(формы.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 ответ

Хорошо, я понял это, это было действительно довольно просто. Я включил этот JavaScript как последнюю вещь перед закрывающим тегом html в моем файле base.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 не отображаются, но сообщения проверки отображаются по мере того, как пользователь заполняет поле, что мне действительно нужно. Надеюсь, кто-то еще найдет это, чтобы им не приходилось складывать голову так долго, как я.

Другие вопросы по тегам