Reputation: 746
I tried many ways to validate forms using Django. but It cannot validate a Django form I see much documentation and many videos to implement validation in form. but it won't work. anybody can give the solution.
1. How many ways to handle form validation using Django?
2. which is the best way to handle form validation using Django?
I tried this way to handle validation error. but it cannot work
my code
forms.py
from django.core.validators import validate_slug,validate_email
from django import forms
from .validators import validatenames
class validform(forms.Form):
firstname = forms.CharField(max_length=10)
class Meta:
fields = ['firstname']
def clean_firstname(self):
name = self.cleaned_data.get('firstname')
name_req = 'hari'
if not name_req in name:
raise forms.ValidationError("Not a name")
return name
views.py
from django.shortcuts import render
from .forms import validform
# Create your views here.
def index(request):
form = validform()
return render(request,'index.html',{'form':form})
index.html
<form>
{{ form.as_p }}
<input type="submit" value="submit">
</form>
I tried another way to handle validation error. this also cannot work
my code
forms.py
from django.core.validators import validate_slug,validate_email
from django import forms
from .validators import validatenames
class validform(forms.Form):
firstname = forms.CharField((validators=[validatenames]))
class Meta:
fields = ['firstname']
views.py
from django.shortcuts import render
from .forms import validform
# Create your views here.
def index(request):
form = validform()
return render(request,'index.html',{'form':form})
index.html
<form>
{{ form.as_p }}
<input type="submit" value="submit">
</form>
validators.py
from django.core.exceptions import ValidationError
def validatenames(value):
if not 'hari' in value:
raise ValidationError("Not a name")
return value
I cannot where is mistake occured
Upvotes: 0
Views: 498
Reputation: 2212
Django can handle server-side validation for you. The two examples you posted above are two valid ways to do this and they are almost correct. You just need to pass some data to your form to validate. So if you change your view to
# Create your views here.
def index(request):
form = validform(request.GET or None)
return render(request,'index.html',{'form':form})
it will display the error in your html page if the user entered something else than 'hari' in the input.
Server-side means your data is sent to the server and validated there, returnin with an error message or else in the case of data which is not valid.
When we talk about client-side validation this is done by the client (i.e. the user's browser) before the data is sent to the server. This is not handled by django. To accomplish this you can use build-in html5 validation or javascript to write you custom validation methods. Examples for build-in html5 validation is the number input
: If a user enters a letter into such a field and tries to submit the form a bubble appears telling the user that he should enter a valid number. The build in validations are easier to use as the do not require any javascript but do have limitations, e.g. you cannot define you own error messages.
To achieve the validatation in you post with client - side validation you can use the "pattern" attribute of the input. The pattern is a regular expression used for validation. E.g.
<input type="text" pattern="/hari/">
will show a bubble in the browser saying that the input is not a valid pattern if the user tries to submit a form which does not contain "hari" as a first name.
You can add this attribute when creating your form, e.g. by overriding the __init__
method of your form:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['firstname'].widget.attrs.update({'pattern': '/hari/'})
If you want custom messages etc. you need to write javascript.
As you can see client-side validation is quite an extensive subject, maybe you would like to read some docs about this like these, also containing examples.
One final word: Client side validation and server-side validation are not a question of one or the other. You should always use server-side validation as it is much more reliable. Client-side validation is an additional benefit improving user experience but should never be the only validation method.
Upvotes: 1