class CapaForm(forms.Form):
capa = forms.CharField(required=False)
Upon form submission I want to check the format of the capa
field. I want to require the user to enter the capa format correctly as 6 numbers, a dash, and two numbers. (######-##)
def search(self):
capa = self.cleaned_data.get('capa', None)
if ("\d{6}\-\d{2}" or None) not in capa:
raise forms.ValidationError("CAPA format needs to be ######-##!")
It's currently not letting me submit a correctly formatted capa and throws the ValidationError. I think the problem is I'm trying to compare a regular expression to an object. How can I check the format of the 'capa' the user tries to submit?
*********UPDATE
Everything is working now EXCEPT when I type the wrong format in the CAPA field. I get the error The view incidents.views.index didn't return an HttpResponse object. It returned None instead.
Is this related to the changes I made?
from django.core.validators import RegexValidator
my_validator = RegexValidator("\d{6}\-\d{2}", "CAPA format needs to be ######-##.")
class CapaForm(forms.Form):
capa = forms.CharField(
label="CAPA",
required=False, # Note: validators are not run against empty fields
validators=[my_validator]
)
def search(self):
capa = self.cleaned_data.get('capa', None)
query = Incident.objects.all()
if capa is not '':
query = query.filter(capa=capa)
return(query)
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute. Let's see an example that takes user input and validate input as well.
The run_validators() method on a Field runs all of the field's validators and aggregates all the errors into a single ValidationError .
The clean_<fieldname>() method: Use this method when you want to do a cleaning on a form field attribute unrelated to the type of the field. For example, you want to make sure that a particular field is unique.
If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file. At you model, the setting title/content = CharField(null=True, blank=True) doesn´t work? At your model-form have you tried setting title/content = forms.
First you need a regex validator: Django validators / regex validator
Then, add it into the validator list of your field: using validators in forms
Simple example below:
from django.core.validators import RegexValidator
my_validator = RegexValidator(r"A", "Your string should contain letter A in it.")
class MyForm(forms.Form):
subject = forms.CharField(
label="Test field",
required=True, # Note: validators are not run against empty fields
validators=[my_validator]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With