Skip to content

DocumentFormSet modification leads to NotUniqueError #75

@MisterFreeze

Description

@MisterFreeze

First, let me thank you for this nice library.

I am migrating a project from django models to django mongoengine documents and I am using django-mongodbforms 0.3 as a replacement for the django forms for models. The migration is seamless so far.

I just tried to update a set of forms constructed from a supplied queryset in this way:

    formset_constructor = document_formset_factory(document_class, max_num=1, **formset_kwargs)
    qs = docucment_class.objects.filter(id=obj_id)
    formset_check = formset_constructor(request.POST, queryset=qs)
    if formset_check.is_valid():
        for inst in formset_check.save(commit=False):
            # do something
            inst.save()

The document class has a unique constraint on a field and the inst.save() raises a NotUniqueError (for that field, if value is unchanged).

I think this happens because the instance is freshly constructed during the is_valid() execution and the id value is not copied to that new instance in construct_instance(), which is called by _post_clean().
In fields_for_document(), any ObjectIdField is skipped. ObjectIdFields are skipped in construct_instance() as well. When I remove

    if isinstance(f, ObjectIdField):
        continue

in both functions, the inst.save() succeeds without raising that NotUniqueError.

I think that this is a common use case. Did I do something wrong here?

Best regards,

Chris

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions