Enhanced Forms

Django forms provide a convenient way to handle user input and data validation. In this project’s context, forms will allow us to receive data from clients through REST API endpoints and to validate it before we create new objects in our database.

In order to enhance the capabilities of Django Forms there are implementations of ModelField and ManyToManyField as fields for form classes.

To get started with the new form fields we’ve just introduced, let’s create a new form class that will define the fields we want to receive from the client. Here’s an example:

1from django import forms
2from mastf.MASTF.forms import ModelField
3from .models import MyModel
4
5class SampleForm(forms.Form):
6    field1 = ModelField(MyModel, mapper=int)
7    field2 = forms.CharField(...)

In this example, we create a new form class called SampleForm that inherits from forms.Form. we define a ModelField that will use an incoming integer value as the primary key search value.

Note

Values of ModelField and ManyToManyField fields should be transmitted as string values as these fields expect a string as input. You can define a mapper function to convert an input string into your preferred primary key value.

Enhanced Fields

class mastf.MASTF.forms.ModelField(model, field_name='pk', mapper=None, **kwargs)[source]

To apply foreign-key references, just use the ModelField.

>>> class ExampleForm(forms.Form):
...    user = ModelField(User, mapper=int)
>>> # The cleaned data will store the referenced User instance
>>> POST = {'user': "1"}
>>> form = ExampleForm(POST)
>>> if form.is_valid():
...     cleaned = form.cleaned_data
...     user = cleaned['user']
...     print(user.username)
Parameters:
  • model (class<? extends Model>) – The Django model class

  • field_name (str) – The field name to query

  • mapper (Callable[T, [str]]) – A conversion function to optionally convert input key

clean(value) object[source]

Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.

class mastf.MASTF.forms.ManyToManyField(model, field_name='pk', delimiter: str = ',', mapper=None, **kwargs)[source]

Implementation of a Many-To-Many relation for Django forms.

This class aims to enhance the capabilities of Django forms by providing a way to include Many-To-Many relationships. This field is represented by a string that cancatenates the primary keys of the referenced objects.

This field may be used within a form class to specify a Many-To-Many relationship:

1class AuthorForm(forms.Form):
2    books = ManyToManyField(Book, mapper=int, required=False)
3    name = forms.CharField(max_length=50, required=True)

The cleaned data of the previously defined form would contain all Book objects that have been referenced in the request. Note that we have to provide a mapping function to convert the string values to integer primary keys.

For instance, the following code uses the form to retrieve all Book objects that are needed:

1POST = {"name": "Foo", "books": "1,2,3,4"}
2form = AuthorForm(data=POST)
3if form.is_valid():
4    data = form.cleaned_data
5    # The returned value is a list storing all referenced
6    # Book objects.
7    books = data.pop('books')
Parameters:
  • model (class<? extends Model>) – The Django model class

  • delimiter (str) – The string delimiter to use when splitting the input string

  • field_name (str) – The field name to query

  • mapper (Callable[T, [str]]) – A conversion function to optionally convert input keys

clean(value: str) list[source]

Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.

convert_id(raw_id)[source]

Converts the given raw id - by default, it returns the raw id