All Projects → tj-django → django-extra-field-validation

tj-django / django-extra-field-validation

Licence: Apache-2.0, MIT licenses found Licenses found Apache-2.0 LICENSE-APACHE MIT LICENSE-MIT
Extends the Django model with required, conditional, and optional field validation.

Programming Languages

python
139335 projects - #7 most used programming language
Makefile
30231 projects

Projects that are alternatives of or similar to django-extra-field-validation

django api forms
Declarative Django request validation for RESTful APIs
Stars: ✭ 17 (-5.56%)
Mutual labels:  django-forms, django-validators
django-siteforms
Django reusable app to simplify form construction
Stars: ✭ 15 (-16.67%)
Mutual labels:  django-application
soak-your-brain-elearning-app
An e-learning platform built in python (django)
Stars: ✭ 18 (+0%)
Mutual labels:  django-application
django-survey
A django survey app that can export results as CSV or PDF using your native language.
Stars: ✭ 178 (+888.89%)
Mutual labels:  django-application
Django-CRM-Project
Django CRM Project - Youtube Tutorial
Stars: ✭ 108 (+500%)
Mutual labels:  django-application
Django-Verify-Email
A two-step verification for new accounts by verifying email.
Stars: ✭ 51 (+183.33%)
Mutual labels:  django-application
PyEditorial
A free, open-source Blog CMS based on the "Django" and "Editorial" HTML5 theme.
Stars: ✭ 178 (+888.89%)
Mutual labels:  django-application
django-lock-tokens
A Django application that provides a locking mechanism to prevent concurrency editing.
Stars: ✭ 19 (+5.56%)
Mutual labels:  django-application
wagtailmath
Beautiful equations in your StreamField content
Stars: ✭ 27 (+50%)
Mutual labels:  django-application
django-front-end-validators
Use model field validator functions for front end JS form validation
Stars: ✭ 15 (-16.67%)
Mutual labels:  django-forms
DjanGoat
Python and Django implementation of the OWASP RailsGoat project
Stars: ✭ 65 (+261.11%)
Mutual labels:  django-application
django-proxypay
Django Proxypay is a Django Framework application/library that facilitates the integration of your Django project with the Proxypay API.
Stars: ✭ 14 (-22.22%)
Mutual labels:  django-application
mubapp
MUB is a multi-user blog web app using the Python-Django infrastructure.
Stars: ✭ 24 (+33.33%)
Mutual labels:  django-application
xlsx over web
Django开发的excel表格展示系统,将本地xlsx文件导入到数据库,显示到JS页面 online excel manage with django
Stars: ✭ 27 (+50%)
Mutual labels:  django-application
acme2certifier
library implementing ACME server functionality
Stars: ✭ 62 (+244.44%)
Mutual labels:  django-application
django-simple-forum
full featured forum, easy to integrate and use.
Stars: ✭ 65 (+261.11%)
Mutual labels:  django-application
Deep-learning-model-deploy-with-django
Serving a keras model (neural networks) in a website with the python Django-REST framework.
Stars: ✭ 76 (+322.22%)
Mutual labels:  django-application
PyShop
PyShop is an online Python Ecommerce website built with Django, SQLite and Bootstrap. A simple and lightweight ecommerce app easily deployable anywhere anytime with modules developed upon the inbuilt django admin.
Stars: ✭ 17 (-5.56%)
Mutual labels:  django-application
django-renderpdf
📄 A Django app to render django templates as PDF files.
Stars: ✭ 37 (+105.56%)
Mutual labels:  django-application
python-web-dev-21-2
Material for "Web Development in Python with Django" using Django 2.1, published as a Pearson LiveLesson on Safari Books Online
Stars: ✭ 38 (+111.11%)
Mutual labels:  django-application

django-extra-field-validation

PyPI PyPI - Python Version PyPI - Django Version Downloads

CI Test Codacy Badge Codacy Badge Total alerts Language grade: Python

Table of Contents

Background

This package aims to provide tools needed to define custom field validation logic which can be used independently or with django forms, test cases, API implementation or any model operation that requires saving data to the database.

This can also be extended by defining check constraints if needed but currently validation will only be handled at the model level.

Installation

pip install django-extra-field-validation

Usage

Require all fields

from django.db import models
from extra_validator import FieldValidationMixin


class TestModel(FieldValidationMixin, models.Model):
    amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    fixed_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)

    REQUIRED_FIELDS = ['amount']  # Always requires an amount to create the instance.

Example

In [1]: from decimal import Decimal

In [2]: from demo.models import TestModel

In [3]: TestModel.objects.create(fixed_price=Decimal('3.00'))
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {'amount': ValidationError([u'Please provide a value for: "amount".'])}

Require at least one field in a collection

from django.db import models
from extra_validator import FieldValidationMixin


class TestModel(FieldValidationMixin, models.Model):
    amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    fixed_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)

    REQUIRED_TOGGLE_FIELDS = [
        ['amount', 'fixed_price', 'percentage'],  # Require only one of the following fields.
    ]

Example

In [1]: from decimal import Decimal

In [2]: from demo.models import TestModel

In [3]: TestModel.objects.create(amount=Decimal('2.50'), fixed_price=Decimal('3.00'))
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {'fixed_price': ValidationError([u'Please provide only one of: Amount, Fixed price, Percentage'])}

Optionally require at least one field in a collection

from django.db import models
from extra_validator import FieldValidationMixin


class TestModel(FieldValidationMixin, models.Model):
    amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    fixed_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)

    OPTIONAL_TOGGLE_FIELDS = [
        ['fixed_price', 'percentage']  # Optionally validates that only fixed price/percentage are provided when present.
    ]

Example

In [1]: from decimal import Decimal

In [2]: from demo.models import TestModel

In [3]: first_obj = TestModel.objects.create(amount=Decimal('2.0'))

In [4]: second_obj = TestModel.objects.create(amount=Decimal('2.0'), fixed_price=Decimal('3.00'))

In [5]: third_obj = TestModel.objects.create(amount=Decimal('2.0'), fixed_price=Decimal('3.00'), percentage=Decimal('10.0'))
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {'percentage': ValidationError([u'Please provide only one of: Fixed price, Percentage'])}

Conditionally require all fields

from django.db import models
from django.conf import settings
from extra_validator import FieldValidationMixin


class TestModel(FieldValidationMixin, models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    fixed_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)

    CONDITIONAL_REQUIRED_FIELDS = [
        (
            lambda instance: instance.user.is_active, ['amount', 'percentage'],
        ),
    ]

Example

In [1]: from decimal import Decimal

in [2]: from django.contrib.auth import get_user_model

In [3]: from demo.models import TestModel

In [4]: user = get_user_model().objects.create(username='test', is_active=True)

In [5]: first_obj = TestModel.objects.create(user=user, amount=Decimal('2.0'))
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {u'percentage': ValidationError([u'Please provide a value for: "percentage"'])}

Conditionally require at least one field in a collection

from django.db import models
from django.conf import settings
from extra_validator import FieldValidationMixin


class TestModel(FieldValidationMixin, models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    fixed_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
    percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)

    CONDITIONAL_REQUIRED_TOGGLE_FIELDS = [
        (
            lambda instance: instance.user.is_active, ['fixed_price', 'percentage', 'amount'],
        ),
    ]

Example

In [1]: from decimal import Decimal

in [2]: from django.contrib.auth import get_user_model

In [3]: from demo.models import TestModel

In [4]: user = get_user_model().objects.create(username='test', is_active=True)

In [5]: first_obj = TestModel.objects.create(user=user)
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {'__all__': ValidationError([u'Please provide a valid value for any of the following fields: Fixed price, Percentage, Amount'])}

In [6]: second_obj = TestModel.objects.create(user=user, amount=Decimal('2'), fixed_price=Decimal('2'))
---------------------------------------------------------------------------
ValueError                   Traceback (most recent call last)
...

ValueError: {'__all__': ValidationError([u'Please provide only one of the following fields: Fixed price, Percentage, Amount'])}

Model Attributes

This is done using model attributes below.

# A list of required fields
REQUIRED_FIELDS = []

#  A list of fields with at most one required.
REQUIRED_TOGGLE_FIELDS = []

# A list of field with at least one required.
REQUIRED_MIN_FIELDS = []

# Optional list of fields with at most one required.
OPTIONAL_TOGGLE_FIELDS = []

# Conditional field required list of tuples the condition a boolean or a callable.
# [(lambda user: user.is_admin, ['first_name', 'last_name'])] : Both 'first_name' or 'last_name'
# If condition is True ensure that all fields are set
CONDITIONAL_REQUIRED_FIELDS = []

# [(lambda user: user.is_admin, ['first_name', 'last_name'])] : Either 'first_name' or 'last_name'
# If condition is True ensure that at most one field is set
CONDITIONAL_REQUIRED_TOGGLE_FIELDS = []

# [(lambda user: user.is_admin, ['first_name', 'last_name'])] : At least 'first_name' or 'last_name' provided or both
# If condition is True ensure that at least one field is set
CONDITIONAL_REQUIRED_MIN_FIELDS = []

# [(lambda user: user.is_admin, ['first_name', 'last_name'])] : Both 'first_name' and 'last_name' isn't provided
# If condition is True ensure none of the fields are provided
CONDITIONAL_REQUIRED_EMPTY_FIELDS = []

License

django-extra-field-validation is distributed under the terms of both

at your option.

TODO's

  • Support CONDITIONAL_NON_REQUIRED_TOGGLE_FIELDS
  • Support CONDITIONAL_NON_REQUIRED_FIELDS
  • Move to support class and function based validators that use the instance object this should enable cross field model validation.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].