-
Notifications
You must be signed in to change notification settings - Fork 20
INTPYTHON-483 Add EmbeddedModelArrayField #292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from django.db.models import Field | ||
|
||
from .. import forms | ||
from . import EmbeddedModelField | ||
from .array import ArrayField | ||
|
||
|
||
class EmbeddedModelArrayField(ArrayField): | ||
def __init__(self, embedded_model, **kwargs): | ||
if "size" in kwargs: | ||
raise ValueError("EmbeddedModelArrayField does not support size.") | ||
super().__init__(EmbeddedModelField(embedded_model), **kwargs) | ||
self.embedded_model = embedded_model | ||
|
||
def deconstruct(self): | ||
name, path, args, kwargs = super().deconstruct() | ||
if path == "django_mongodb_backend.fields.embedded_model_array.EmbeddedModelArrayField": | ||
path = "django_mongodb_backend.fields.EmbeddedModelArrayField" | ||
kwargs["embedded_model"] = self.embedded_model | ||
del kwargs["base_field"] | ||
return name, path, args, kwargs | ||
|
||
def get_db_prep_value(self, value, connection, prepared=False): | ||
if isinstance(value, list | tuple): | ||
# Must call get_db_prep_save() rather than get_db_prep_value() | ||
# to transform model instances to dicts. | ||
return [self.base_field.get_db_prep_save(i, connection) for i in value] | ||
if value is not None: | ||
raise TypeError( | ||
f"Expected list of {self.embedded_model!r} instances, not {type(value)!r}." | ||
) | ||
return value | ||
|
||
def formfield(self, **kwargs): | ||
# Skip ArrayField.formfield() which has some differences, including | ||
# unneeded "base_field", and "max_length" instead of "max_num". | ||
return Field.formfield( | ||
self, | ||
**{ | ||
"form_class": forms.EmbeddedModelArrayField, | ||
"model": self.embedded_model, | ||
"max_num": self.max_size, | ||
"prefix": self.name, | ||
**kwargs, | ||
}, | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
django_mongodb_backend/forms/fields/embedded_model_array.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
from django import forms | ||
from django.core.exceptions import ValidationError | ||
from django.forms import formset_factory, model_to_dict | ||
from django.forms.models import modelform_factory | ||
from django.utils.html import format_html, format_html_join | ||
|
||
|
||
class EmbeddedModelArrayField(forms.Field): | ||
def __init__(self, model, *, prefix, max_num=None, extra_forms=3, **kwargs): | ||
self.model = model | ||
self.prefix = prefix | ||
self.formset = formset_factory( | ||
form=modelform_factory(model, fields="__all__"), | ||
can_delete=True, | ||
max_num=max_num, | ||
extra=extra_forms, | ||
validate_max=True, | ||
) | ||
kwargs["widget"] = EmbeddedModelArrayWidget() | ||
super().__init__(**kwargs) | ||
|
||
def clean(self, value): | ||
if not value: | ||
return [] | ||
formset = self.formset(value, prefix=self.prefix_override or self.prefix) | ||
if not formset.is_valid(): | ||
raise ValidationError(formset.errors + formset.non_form_errors()) | ||
cleaned_data = [] | ||
for data in formset.cleaned_data: | ||
# The "delete" checkbox isn't part of model data and must be | ||
# removed. The fallback to True skips empty forms. | ||
if data.pop("DELETE", True): | ||
continue | ||
cleaned_data.append(self.model(**data)) | ||
return cleaned_data | ||
|
||
def has_changed(self, initial, data): | ||
formset = self.formset(data, initial=models_to_dicts(initial), prefix=self.prefix) | ||
return formset.has_changed() | ||
|
||
def get_bound_field(self, form, field_name): | ||
# Nested embedded model form fields need a double prefix. | ||
# HACK: Setting self.prefix_override makes it available in clean() | ||
# which doesn't have access to the form. | ||
self.prefix_override = f"{form.prefix}-{self.prefix}" if form.prefix else None | ||
timgraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return EmbeddedModelArrayBoundField(form, self, field_name, self.prefix_override) | ||
|
||
|
||
class EmbeddedModelArrayBoundField(forms.BoundField): | ||
def __init__(self, form, field, name, prefix_override): | ||
super().__init__(form, field, name) | ||
self.formset = field.formset( | ||
self.data if form.is_bound else None, | ||
initial=models_to_dicts(self.initial), | ||
prefix=prefix_override if prefix_override else self.html_name, | ||
) | ||
|
||
def __str__(self): | ||
body = format_html_join( | ||
"\n", "<tbody>{}</tbody>", ((form.as_table(),) for form in self.formset) | ||
) | ||
return format_html("<table>\n{}\n</table>\n{}", body, self.formset.management_form) | ||
|
||
|
||
class EmbeddedModelArrayWidget(forms.Widget): | ||
""" | ||
Extract the data for EmbeddedModelArrayFormField's formset. | ||
This widget is never rendered. | ||
""" | ||
|
||
def value_from_datadict(self, data, files, name): | ||
return {field: value for field, value in data.items() if field.startswith(f"{name}-")} | ||
|
||
|
||
def models_to_dicts(models): | ||
""" | ||
Convert initial data (which is a list of model instances or None) to a | ||
list of dictionary data suitable for a formset. | ||
""" | ||
return [model_to_dict(model) for model in models or []] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.