Skip to content

Commit

Permalink
add: laytou improvments for one-to-one inline-formsets
Browse files Browse the repository at this point in the history
  • Loading branch information
saemideluxe committed Aug 18, 2023
1 parent b0cf8b8 commit 1c33aa3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
41 changes: 41 additions & 0 deletions basxbread/layout/components/forms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,47 @@ def as_datatable(
formsetelem.management_form,
)

@staticmethod
def as_fieldset(
formset,
fields: List,
title: Optional[str] = None,
formsetfield_kwargs: Optional[dict] = None,
fieldname=None, # required for inline-formsets
can_add=True,
**kwargs,
) -> hg.BaseElement:
formsetelem = Formset(
formset,
hg.DIV(*[(FormField(f) if isinstance(f, str) else f) for f in fields]),
**({"fieldname": fieldname} if fieldname else {}),
**(formsetfield_kwargs or {}),
)
id = hg.html_id(formsetelem, prefix="formset-")

return hg.BaseElement(
hg.If(
formset.non_form_errors(),
hg.Iterator(
formset.non_form_errors(),
"formerror",
InlineNotification(
_("Form error"), hg.C("formerror"), kind="error"
),
),
),
hg.FIELDSET(hg.H4(title), formsetelem, id=id),
formsetelem.management_form,
formsetelem.add_button(
buttontype="ghost",
notext=False,
label="+",
container_css_selector=f"#{id}",
)
if can_add
else None,
)


class DeleteButton(Button):
def __init__(self, parentcontainerselector, label=_("Delete"), **kwargs):
Expand Down
9 changes: 8 additions & 1 deletion basxbread/views/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django import forms
from django.conf import settings
from django.contrib import messages
from django.db import models
from django.http import HttpResponse
from django.urls import NoReverseMatch
from django.utils.html import mark_safe
Expand Down Expand Up @@ -178,8 +179,14 @@ def get_layout(self):
if field in direct_model_formfields:
ret.append(layout.forms.FormField(field))
elif isinstance(field, str) and field in inlineforms:
layout_generator = layout.forms.Formset.as_datatable
if isinstance(
getattr(self.model, field),
models.fields.related_descriptors.ReverseOneToOneDescriptor,
):
layout_generator = layout.forms.Formset.as_fieldset
ret.append(
layout.forms.Formset.as_datatable(
layout_generator(
hg.C("form")[field].formset,
fieldname=field,
title=hg.C("form")[field].label,
Expand Down

0 comments on commit 1c33aa3

Please sign in to comment.