【问题标题】:custom form validation errors in template模板中的自定义表单验证错误
【发布时间】:2020-07-25 13:40:12
【问题描述】:

如何在模板中传递自定义表单验证错误?

forms.py

    def clean_username(self):
    inputusername = self.cleaned_data['username']
    if len(inputusername) < 6:
    raise forms.ValidationError('Sorry, your username must be between 6 and 30 characters long.')
    else:
    return inputusername

views.py

def signup(request):
signup_form = CreateUserForm()
if request.method == 'POST':
signup_form = CreateUserForm(request.POST)
if signup_form.is_valid():
signup_form.save()

context = {'signup_form':signup_form}
return render(request, 'formvalidationapp/signupform.html', context)

模板

<form method="post" action="{% url 'signup' %}">
{% csrf_token %}
<div class="row">
<div class="col-sm-6">
<h1>Sign Up</h1>
</div>
</div>
<div>
#i want to pass error here
</div>

【问题讨论】:

标签: django django-models django-forms django-views django-templates


【解决方案1】:

你可以这样试试

{{signup_form.username.errors}}

【讨论】:

  • 兄弟在这种情况下我该怎么办? def clean_password(self): inputpassword1 = self.cleaned_data['password1'] inputpassword2 = self.cleaned_data['password2'] if inputpassword1 != inputpassword2: raise forms.ValidationError('Password did\'t match') else: return inputpassword1 ,输入密码2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2017-12-02
相关资源
最近更新 更多