[Django]-Django Form with no required fields

6👍

You can create a custom ModelForm that suit your needs. This custom ModelForm will override the save method and set all fields to be non-required:

from django.forms import ModelForm

class SearchForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        for key, field in self.fields.iteritems():
            self.fields[key].required = False

So you could declare your forms by simply calling instead of the ModelForm, e.g.:

class MessageForm(SearchForm):
    class Meta:
        model = Message

2👍

You could also pass empty_permitted=True when you instantiate the form, e.g.,

form = MessageSearch(empty_permitted=True)

that way you can still have normal validation rules for when someone does enter data into the form.

0👍

I would give a try to the django-filter module :

http://django-filter.readthedocs.io/en/develop/

fields are not required. these are filters actually. It would look like this :

import django_filters

class MessageSearch(django_filters.FilterSet):

    class Meta:
        model = Message
        fields = ['happened', 'filename', 'message', '...', ]

    # django-filter has its own default widgets corresponding to the field
    # type of the model, but you can tweak and subclass in a django way :
    happened = django_filters.DateFromToRangeFilter()

mandatory, hidden filters can be defined if you want to narrow a list of model depending on something like user rights etc.

also : setup a filter on a ‘reverse’ relationship (the foreignkey is not in the filtered model : the model is referenced elsewhere in another table), is easy, just name the table where the foreign key of the filtered model field is :

    # the 'tags' model has a fk like message = models.ForeignKey(Message...)
    tags= django_filters.<some filter>(name='tags')

quick extendable and clean to setup.
please note I didn’t wrote this module, I’m just very happy with it 🙂

Leave a comment