#19255: Cannot validate generic foreignkey in new instance
--------------------------------------+--------------------
Reporter: bouke | Owner: nobody
Type: Uncategorized | Status: new
Component: contrib.contenttypes | Version: 1.4
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Easy pickings: 0 | UI/UX: 0
--------------------------------------+--------------------
Given this model:
{{{
class Model(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey()
def clean(self):
assert self.object_id
assert self.object
}}}
and this admin:
{{{
class ModelInline(generic.GenericStackedInline):
model = Model
}}}
When saving a new `Model`, the assertion will fail. The object will not be
linked, nor will the object_id be available to the clean function. This is
because the fields are excluded from the formset and the values are set
through the generic InlineAdmin, see this excerpt:
{{{
generic.py:412
def save_new(self, form, commit=True):
# Avoid a circular import.
from django.contrib.contenttypes.models import ContentType
kwargs = {
self.ct_field.get_attname():
ContentType.objects.get_for_model(self.instance).pk,
self.ct_fk_field.get_attname(): self.instance.pk,
}
new_obj = self.model(**kwargs)
return save_instance(form, new_obj, commit=commit)
}}}
To hack around this issue, the forms and formsets involved should not
cache the validation result. The clean function should then validate the
value if it is present (the second time when cleaning). The hack is quite
ugly and requires a lot of coding. It should be possible to easily
validate the newly related-to foreign key object.
--
Ticket URL: <https://code.djangoproject.com/ticket/19255>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.