-1

How can I pass custom form validation errors in template?

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)

temlate

<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>
yacc
  • 2,915
  • 4
  • 19
  • 33
  • Does this answer your question? [Django Forms: if not valid, show form with error message](https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message) – Lbatson Apr 13 '20 at 20:25

1 Answers1

1

You can try like this

{{signup_form.username.errors}}
arjun
  • 7,230
  • 4
  • 12
  • 29
  • bro in this case how can i do? def clean_password(self): inputpassword1 = self.cleaned_data['password1'] inputpassword2 = self.cleaned_data['password2'] if inputpassword1 != inputpassword2: raise forms.ValidationError('Password didn\'t match') else: return inputpassword1,inputpassword2 –  Apr 13 '20 at 03:11