Is it possible to do the following?

I have a formset which have 10 forms. In each form, there are 3 fields. moduletype, firstportid, lastportid. Each id for the forms are deviceinterface-set(form number)-field. In my case, user must key in the following format for firstportid and lastportid : int/int/int. Example: 1/0/1 for firstportid and 1/0/5 for lastportid. But the 1st int and the middle int can be 1-18 & 1-4. The last int can be between 1 to 48. Is there a fast way to check the formset for the following instead of getting the values from the field one by one to check.

An example: In the formset i filled up 2 out of the 10 forms. For the 1st form, my values are 5/0/1 (firstportid) and 5/0/5 (lastportid). For the 2nd form, it will be 4/2/1 (firstportid) and 4/2/10 (lastportid). Instead of getting the values one by one from form and then the field in the form. Is there some way for me to loop thru to get the values fast? For now i can only think of getting the values one by one from each of the form. Such as breaking down the values to extract a single number and do what i need

I am not completely sure I understand what do you want to do, but i think you should try to accomplish a first verification at FrontEnd level with Javascript.

know if you want to check the fields without create a manual loop in the form validation you can add validators to your models or your forms. IMHO for what you want to achieve you should use the built-in RegexValidator in the fields moduletype, firstportid, lastportid of your model , for example I coded this for a project:

from django.core.validators import RegexValidator
#...

class MyModel(models.Model):
   # ...
   contact_phone_number = models.CharField(
        verbose_name=_("contact_phone_number"),
        max_length=15,
        help_text=_(
            "Provide a phone number from El Salvador in order to contact on emergencies."
        ),
        validators=[
            RegexValidator(
                "^\(503\)\s[267]\d{3}-\d{4}$",
                _("This is not a valid phone number for El Salvador."),
            )
        ],
        null=True,
    )
   # ...

In your case you max_length should be 7 and your regular expression must be adapted to the desired format.

Thank you very much. I did the logic check in views instead, if else loop. Is it a good practice to do it there?

No, in fact is consider a bad practice.
See this:

https://sunscrapers.com/blog/where-to-put-business-logic-django/

That is not a dogma, but IMHO you should try to follow the next order in logic of your apps in a wider perspective:Managers, custom model fields, helpers functions(as validators), models, mixins or decorators, forms, views and finally templates.

The view’s ok, but putting it in validators within the form may be more appropriate. That way you can reject an invalid form entry from within the context of the form-handling view.

Oh okay. Thanks for answering :slight_smile:

Thank you very much :slight_smile: