Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
nested form for adding title children
  • Loading branch information
zxenia committed Mar 20, 2019
1 parent bd82b74 commit e71fa51
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 3 deletions.
Binary file modified db.sqlite3
Binary file not shown.
3 changes: 2 additions & 1 deletion mycollections/admin.py
Expand Up @@ -3,4 +3,5 @@
# Register your models here.

admin.site.register(Collection)
admin.site.register(CollectionTitle)
admin.site.register(CollectionTitle)
admin.site.register(CollectionTitleChild)
45 changes: 43 additions & 2 deletions mycollections/forms.py
Expand Up @@ -4,6 +4,41 @@
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Fieldset, Div, HTML, ButtonHolder, Submit
from .custom_layout_object import *
from django.forms.models import BaseInlineFormSet


CollectionTitleChildFormSet = inlineformset_factory(
CollectionTitle, CollectionTitleChild,
fields=['name', 'language'], extra=2, can_delete=True

This comment has been minimized.

Copy link
@jgarzautexas

jgarzautexas Apr 3, 2020

Just curious, how can I implement this if I needed to add a form here in the CollectionTitleChildFormset, that was dynamically built (adding fields in the init method ) like below.

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["my_dynamic_field_1"]` = forms.FloatField()

the CollectionTitleChildFormSet could look like this I suppose:

CollectionTitleChildFormSet = inlineformset_factory(CollectionTitle, CollectionTitleChild, form=MyDynamicForm

but what about the BaseTitleChildFormset that is build using form.nested = CollectionTitleChildFormSet?
Seems this is wanting the CollectionTitleChildFormSet to already be built.

thanks for the help.

)


class BaseTitleChildFormset(BaseInlineFormSet):

def add_fields(self, form, index):
super(BaseTitleChildFormset, self).add_fields(form, index)

# save the formset in the 'nested' property
form.nested = CollectionTitleChildFormSet(
instance=form.instance,
data=form.data if form.is_bound else None,
prefix='child-%s-%s' % (form.prefix, CollectionTitleChildFormSet.get_default_prefix()))

def is_valid(self):
result = super(BaseTitleChildFormset, self).is_valid()
if self.is_bound:
for form in self.forms:
if hasattr(form, 'nested'):
result = result and form.nested.is_valid()
return result

def save(self, commit=True):
result = super(BaseTitleChildFormset, self).save(commit=commit)
for form in self.forms:
if hasattr(form, 'nested'):
if not self._should_delete_form(form):
form.nested.save(commit=commit)
return result


class CollectionTitleForm(forms.ModelForm):
Expand All @@ -12,10 +47,16 @@ class Meta:
model = CollectionTitle
exclude = ()

# CollectionTitleFormSet = inlineformset_factory(
# Collection, CollectionTitle, form=CollectionTitleForm,
# fields=['name', 'language'], extra=1, can_delete=True
# )

CollectionTitleFormSet = inlineformset_factory(
Collection, CollectionTitle, form=CollectionTitleForm,
fields=['name', 'language'], extra=1, can_delete=True
)
formset=BaseTitleChildFormset,
fields=['name', 'language'], extra=1, can_delete=True)



class CollectionForm(forms.ModelForm):
Expand Down
23 changes: 23 additions & 0 deletions mycollections/migrations/0003_collectiontitlechild.py
@@ -0,0 +1,23 @@
# Generated by Django 2.1.7 on 2019-03-20 19:34

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('mycollections', '0002_auto_20190213_1141'),
]

operations = [
migrations.CreateModel(
name='CollectionTitleChild',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=500, verbose_name='Child')),
('language', models.CharField(max_length=3)),
('collection_title', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='has_children', to='mycollections.CollectionTitle')),
],
),
]
12 changes: 12 additions & 0 deletions mycollections/models.py
Expand Up @@ -23,3 +23,15 @@ class CollectionTitle(models.Model):
related_name="has_titles", on_delete=models.CASCADE)
name = models.CharField(max_length=500, verbose_name="Title")
language = models.CharField(max_length=3)


class CollectionTitleChild(models.Model):
"""
A Class for Collection title children.
"""
collection_title = models.ForeignKey(CollectionTitle,
related_name="has_children", on_delete=models.CASCADE)
name = models.CharField(max_length=500, verbose_name="Child")
language = models.CharField(max_length=3)

8 changes: 8 additions & 0 deletions mycollections/templates/mycollections/collection_detail.html
Expand Up @@ -13,6 +13,14 @@ <h1><b>Collection ID {{ object }}</b></h1>
<th>Title @{{title.language}}</th>
<td>{{title.name}}</td>
</tr>
{% if title.has_children.all %}
{% for child in title.has_children.all %}
<tr>
<th>Child @{{child.language}}</th>
<td>{{child.name}}</td>
</tr>
{% endfor %}
{% endif %}
{% endfor %}
{% endif %}
<!--end-->
Expand Down
35 changes: 35 additions & 0 deletions mycollections/templates/mycollections/formset.html
Expand Up @@ -17,7 +17,35 @@
{{ field|as_crispy_field }}
</td>
{% endfor %}

</tr>
<!--nested form-->
{% if form.nested %}
{{ form.nested.management_form }}
{{ form.nested.non_form_errors }}

{% for nested_form in form.nested.forms %}

<tr class="{% cycle 'row1' 'row2' %} formset_child-{{ formset.prefix }}"">
{% for field in nested_form.visible_fields %}
<td>
{# Include the hidden fields in the nested_form #}
{% if forloop.first %}
{% for hidden in nested_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field|as_crispy_field }}
</td>
{% endfor %}
</tr>

{% endfor %}

{% endif %}
<!-- end of nested form-->

{% endfor %}

</table>
Expand All @@ -30,4 +58,11 @@
deleteText: 'remove',
prefix: '{{ formset.prefix }}',
});
</script>
<script type="text/javascript">
$('.formset_child-{{ formset.prefix }}').formset({
addText: 'add child',
deleteText: 'remove',
prefix: '{{ formset.prefix }}',
});
</script>
1 change: 1 addition & 0 deletions mycollections/views.py
Expand Up @@ -56,6 +56,7 @@ def form_valid(self, form):
if titles.is_valid():
titles.instance = self.object
titles.save()

return super(CollectionCreate, self).form_valid(form)

def get_success_url(self):
Expand Down

0 comments on commit e71fa51

Please sign in to comment.