如何在django中显示验证消息?

时间:2016-08-15 20:51:44

标签: python django

我试图找到一种方式来显示消息,例如"这个字段是必需的。"同样的方式django默认电子邮件无效的电子邮件。你能帮帮我吗?

This is the way I want to display required field messages.

我的forms.py看起来像:

class NewAccountForm(forms.Form):
    first_name = forms.CharField(max_length=20, required=True)
    email = forms.EmailField(max_length=30, required=True)
    def __init__(self, *args, **kwargs):
        super(NewAccountForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].label = "First Name"
        self.fields['email'].label = "e-mail"
        for name, field in self.fields.items():
            field.widget.attrs['class'] = ' form-control'

并且view.py:

def request_account(request):

  if request.method == 'GET':
    form = NewAccountForm()
  else:
    form = NewAccountForm(request.POST) 

    if form.is_valid():
        email = form.cleaned_data['email']

  return render(request, 'portal/request_account.html', {'form': form,})

我在模板中循环遍历字段:

        {% for field in form %}
            <div class="form-group">
                <div class="col-sm-3">
                    <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
                </div>

                <div class="col-sm-9">
                    {{field}}
                </div>
            </div>
            {{field.non_field_errors }}
            {{field.errors}}
        {% endfor %}

感谢您的帮助!

0 个答案:

没有答案