Skip to content

Instantly share code, notes, and snippets.

@maddrum
Last active January 3, 2023 19:59
Show Gist options
  • Save maddrum/10c54f8375131366fe5144d5e54ff167 to your computer and use it in GitHub Desktop.
Save maddrum/10c54f8375131366fe5144d5e54ff167 to your computer and use it in GitHub Desktop.
Django formset with custom model manager
from django.forms import BaseModelFormSet
from app.companies.models import CompanyBranchPaymentOptions
class PaymentsBaseFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__full_id_queryset = CompanyBranchPaymentOptions.objects.get_full_queryset()
def add_fields(self, form, index):
# When Django adds the "id" ModelChoicefield to form fields/which marks if it is CREATE or UPDATE operation/,
# it uses the get_queryset method of the model manager.
# When that method is overwritten to skip some items /like active=False/ on one hand
# and if the form itself include those skipped items on the other hand,
# this leads to validation error since the provided "id" is not on the ModelChoicefield queryset
# This hook method is perfect to override the default queryset to include missing items.
# Override this after form is ready and replace the original QS with the one that includes missing items.
super().add_fields(form=form, index=index)
form.fields['id'].queryset = self.__full_id_queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment