Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Checking CharField format in form with a regular expression

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)
like image 206
user1807271 Avatar asked Jul 29 '15 15:07

user1807271


People also ask

How do I check if a form is valid in Django?

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.

Which method has a form instance which runs validation routines for all its fields?

The run_validators() method on a Field runs all of the field's validators and aggregates all the errors into a single ValidationError .

What is clean method in Django?

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.

How do you remove this field is required Django?

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.


1 Answers

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]
    )
like image 183
Art Avatar answered Sep 28 '22 01:09

Art