Skip to main content

Additional Logic on Forms

Project description

in forms.py

from alo import forms
from alo.operators import AND, OR

class BookForm(forms.QueryForm):
    # Django form fields
    year   = forms.IntegerField(required=False, min_value=1970, max_value=2012)
    title  = forms.CharField(required=False)
    genre  = forms.CharField(required=False)
    author = forms.CharField(required=False)
    house  = forms.CharField(required=False)

    class Meta:
        lookups = {
            # query_name: model_field__lookups
            'year': 'publication_date__year',
            'title': 'title__icontains',
            'genre': 'genres',
            'author': 'author_id',
            'house': 'publishing_house__id',
        }
        extralogic = [
            # Combine the form fields with boolean logic

            AND('genres', OR('author', 'publishing_house'))
            # if 'genre' provided, so should also be either 'author' or 'house'

            OR('title', 'year', required=True)
            # either 'year' or 'title' must be provided
        ]

class BookModelForm(forms.QueryModelForm):
    class Meta:
        model = Book
        fields = (
            'publication_date', 'title', 'genres',
            'author', 'publishing_house'
        )
        lookups = {
            # query_name: model_field__lookups
            'publication_date': 'publication_date__year',
            'title': 'title__icontains',
        }
        extralogic = [
            # Combine the form fields with boolean logic
            AND('genres', OR('author', 'publishing_house'))
        ]

in views.py

from .forms import BookForm
from .models import Book

def example(request):
    form = BookForm(request.GET)
    if form.is_valid():
        # form.parameters is like form.cleaned_data but
        # with lookups applied and without empty values
        Book.objects.filter(**form.parameters)
        ...
    ...

There is more! Check the full documentation here

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-alo-forms-1.9.0.tar.gz (6.9 kB view hashes)

Uploaded source

Built Distribution

django_alo_forms-1.9.0-py2-none-any.whl (9.4 kB view hashes)

Uploaded py2

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page