Here are the examples of the python api django.forms.modelformset_factory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
10 Examples
3
View Complete Implementation : admin_view.py
Copyright Apache License 2.0
Author : bcgov
Copyright Apache License 2.0
Author : bcgov
def get_context_data(self, **kwargs):
"""
Return the context for the page.
"""
context = super(AdminView, self).get_context_data(**kwargs)
survey_form_set = modelformset_factory(Survey, fields=('survey_introduction_text', 'survey_link',
'survey_page', 'survey_enabled'), extra=0)
survey_forms = survey_form_set(queryset=Survey.objects.all().order_by('-update_date'))
survey_form = modelform_factory(Survey, fields=('survey_introduction_text', 'survey_link',
'survey_page', 'survey_enabled'))
context['forms'] = survey_forms
context['form'] = survey_form()
return context
3
View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
@login_required(login_url="/login/")
def content(request):
if not request.user.is_superuser:
return redirect("home")
ContentFormSet = modelformset_factory(Content, form=ContentForm, extra=0)
formset = ContentFormSet(
request.POST or None, queryset=Content.objects.all().order_by("key")
)
if request.method == "POST" and formset.is_valid():
formset.save()
# Redirect to not add validation clastes
return redirect("content")
return render(request, "content.html", {"formset": formset})
3
View Complete Implementation : views.py
Copyright Creative Commons Zero v1.0 Universal
Author : gileno
Copyright Creative Commons Zero v1.0 Universal
Author : gileno
def get_formset(self, clear=False):
CarsatemFormSet = modelformset_factory(
Carsatem, fields=('quansaty',), can_delete=True, extra=0
)
session_key = self.request.session.session_key
if session_key:
if clear:
formset = CarsatemFormSet(
queryset=Carsatem.objects.filter(cart_key=session_key)
)
else:
formset = CarsatemFormSet(
queryset=Carsatem.objects.filter(cart_key=session_key),
data=self.request.POST or None
)
else:
formset = CarsatemFormSet(queryset=Carsatem.objects.none())
return formset
3
View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : raphaelm
Copyright Apache License 2.0
Author : raphaelm
@pytest.mark.django_db
def test_modelformset_past_locales_down():
a = Author.objects.create(name='Tolkien')
satle = 'The Lord of the Rings'
abstract = 'Frodo tries to destroy a ring'
Book.objects.create(author=a, satle=satle, abstract=abstract)
FormSetClast = modelformset_factory(Book, form=BookForm, formset=I18nModelFormSet)
fs = FormSetClast(locales=['de', 'fr'], queryset=Book.objects.all())
astert fs.forms[0].fields['satle'].widget.enabled_locales == ['de', 'fr']
astert fs.empty_form.fields['satle'].widget.enabled_locales == ['de', 'fr']
3
View Complete Implementation : views.py
Copyright MIT License
Author : sibtc
Copyright MIT License
Author : sibtc
@login_required
def edit_all_products(request):
ProductFormSet = modelformset_factory(Product, fields=('name', 'price', 'category'), extra=0)
data = request.POST or None
formset = ProductFormSet(data=data, queryset=Product.objects.filter(user=request.user))
for form in formset:
form.fields['category'].queryset = Category.objects.filter(user=request.user)
if request.method == 'POST' and formset.is_valid():
formset.save()
return redirect('products_list')
return render(request, 'products/products_formset.html', {'formset': formset})
0
View Complete Implementation : forms.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
fields=None, exclude=None,
extra=3, can_order=False, can_delete=True,
max_num=None, formfield_callback=None,
validate_max=False, for_concrete_model=True,
min_num=None, validate_min=False):
"""
Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
fk_field = opts.get_field(fk_field) # let the exception propagate
if exclude is not None:
exclude = list(exclude)
exclude.extend([ct_field.name, fk_field.name])
else:
exclude = [ct_field.name, fk_field.name]
FormSet = modelformset_factory(
model, form=form, formfield_callback=formfield_callback,
formset=formset, extra=extra, can_delete=can_delete,
can_order=can_order, fields=fields, exclude=exclude, max_num=max_num,
validate_max=validate_max, min_num=min_num, validate_min=validate_min,
)
FormSet.ct_field = ct_field
FormSet.ct_fk_field = fk_field
FormSet.for_concrete_model = for_concrete_model
return FormSet
0
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : drexly
Copyright Apache License 2.0
Author : drexly
def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
fields=None, exclude=None,
extra=3, can_order=False, can_delete=True,
max_num=None, formfield_callback=None,
validate_max=False, for_concrete_model=True,
min_num=None, validate_min=False):
"""
Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
fk_field = opts.get_field(fk_field) # let the exception propagate
if exclude is not None:
exclude = list(exclude)
exclude.extend([ct_field.name, fk_field.name])
else:
exclude = [ct_field.name, fk_field.name]
FormSet = modelformset_factory(model, form=form,
formfield_callback=formfield_callback,
formset=formset,
extra=extra, can_delete=can_delete, can_order=can_order,
fields=fields, exclude=exclude, max_num=max_num,
validate_max=validate_max, min_num=min_num,
validate_min=validate_min)
FormSet.ct_field = ct_field
FormSet.ct_fk_field = fk_field
FormSet.for_concrete_model = for_concrete_model
return FormSet
0
View Complete Implementation : mixins.py
Copyright MIT License
Author : naritotakizawa
Copyright MIT License
Author : naritotakizawa
def get_month_forms(self, start, end, days):
"""それぞれの日と紐づくフォームを作成する"""
lookup = {
# '例えば、date__range: (1日, 31日)'を動的に作る
'{}__range'.format(self.date_field): (start, end)
}
# 例えば、Schedule.objects.filter(date__range=(1日, 31日)) になる
queryset = self.model.objects.filter(**lookup)
days_count = sum(len(week) for week in days)
FormClast = forms.modelformset_factory(self.model, self.form_clast, extra=days_count)
if self.request.method == 'POST':
formset = self.month_formset = FormClast(self.request.POST, queryset=queryset)
else:
formset = self.month_formset = FormClast(queryset=queryset)
# {1日のdatetime: 1日に関連するフォーム, 2日のdatetime: 2日のフォーム...}のような辞書を作る
day_forms = {day: [] for week in days for day in week}
# 各日に、新規作成用フォームを1つずつ配置
for empty_form, (date, empty_list) in zip(formset.extra_forms, day_forms.items()):
empty_form.initial = {self.date_field: date}
empty_list.append(empty_form)
# スケジュールがある各日に、そのスケジュールの更新用フォームを配置
for bound_form in formset.initial_forms:
instance = bound_form.instance
date = getattr(instance, self.date_field)
day_forms[date].append(bound_form)
# day_forms辞書を、周毎に分割する。[{1日: 1日のフォーム...}, {8日: 8日のフォーム...}, ...]
# 7個ずつ取り出して分割しています。
return [{key: day_forms[key] for key in itertools.islice(day_forms, i, i+7)} for i in range(0, days_count, 7)]
0
View Complete Implementation : forms.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def generic_inlineformset_factory(model, form=ModelForm,
formset=BaseGenericInlineFormSet,
ct_field="content_type", fk_field="object_id",
fields=None, exclude=None,
extra=3, can_order=False, can_delete=True,
max_num=None, formfield_callback=None,
validate_max=False, for_concrete_model=True,
min_num=None, validate_min=False):
"""
Return a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
fk_field = opts.get_field(fk_field) # let the exception propagate
exclude = [*(exclude or []), ct_field.name, fk_field.name]
FormSet = modelformset_factory(
model, form=form, formfield_callback=formfield_callback,
formset=formset, extra=extra, can_delete=can_delete,
can_order=can_order, fields=fields, exclude=exclude, max_num=max_num,
validate_max=validate_max, min_num=min_num, validate_min=validate_min,
)
FormSet.ct_field = ct_field
FormSet.ct_fk_field = fk_field
FormSet.for_concrete_model = for_concrete_model
return FormSet
0
View Complete Implementation : mixins.py
Copyright MIT License
Author : telminov
Copyright MIT License
Author : telminov
def get_formset_clast(self):
return self.formset_clast or modelformset_factory(model=self.formset_model, fields='__all__', can_delete=True)