﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34789	"`filter_horizontal` duplicates entries in ""Chosen"" column after instance is added via in another field using the ""plus"" JS action"	Devin Cox	Devin Cox	"Hi there, I noticed a minor frontend bug related to the filter_horizontal tables in the admin console. Here is what I have:

There is a model called Transition with two fields, source and target:

{{{
source = models.ManyToManyField(State, related_name=""transition_source"")
target = models.ForeignKey(State, related_name=""transition_target"", on_delete=models.CASCADE)
}}}

For the admin console, we set filter_horizontal to include 'source'. See ""First Screenshot"" for an example of a given state of a Transition, with ""test"" selected as Source and ""test2"" selected as Target. 

Now, if I add a new State by clicking the ""+"" Icon next to the Target field (let's call it test3), it will add it to both the Target AND the ""Chosen Source"" (see ""Second Screenshot"" for an example).

I will note that upon saving the Transition, it will not actually save ""test3"" to the Chosen Source, meaning that this is an issue only from a UI perspective. After any refresh or save, it will also no longer show in the Chosen Source column. Additionally, there is no issue going the other direction (if I add directly using the ""+"" next to Chosen Source, it will not appear to set the ""Target"" field as well, and it will save properly). Finally, if I were to select another available source (ex. ""test2"") and add it to the Chosen Source, it will successfully add ""test2"" and remove ""test3"" without needing a save or refresh.

I believe this is due to the admin conveniently updating all related fields to include the added object, and therefore displaying it as if it was selected temporarily until refreshed

Diving into this, I believe the issue is in this file: django/django/admin/static/admin/js/admin/RelatedObjectLookups.js

In this function: UpdateRelatedSelectOptions, on this query: 
{{{
const selectsRelated = document.querySelectorAll(`[data-model-ref=""${modelName}""] select:not(.admin-autocomplete)`);
}}}

My initial guess is that updating the query to not include the ""Chosen"" column in filter_horizontal fields would solve this issue (something like 
{{{
const selectsRelated = document.querySelectorAll(`[data-model-ref=""${modelName}""] div:not(.selector-chosen) > select:not(.admin-autocomplete)`);
}}}

Let me know if more context is needed to help reproduce what is going on here. Thanks!"	Bug	closed	contrib.admin	dev	Normal	fixed		David Sanders Marcelo Galigniana	Ready for checkin	1	0	0	0	0	1
