question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

dependent_fields does not work

See original GitHub issue

Hi, First of all thank you for this wonderful Django plugin. I need to create a Chained Model Multiple Select2 , and I have done everything that the documentation asked me to do regarding that. My form looks like this ->

def __init__(self, *args, **kwargs):
		super(NationalFilter, self).__init__(*args, **kwargs)
		# self.fields['state'].choices = getNationalStates()
		# self.fields['district'].choices = getNationalDistricts()
 state = ModelChoiceField(
			queryset = State.objects.all(),
			label = u'State',
			widget = ModelSelect2MultipleWidget(
					model = State,
					search_fields = ['state__icontains']
				)
		)
	district = ModelChoiceField(
			queryset = District.objects.all(),
			label = u'District',
			widget = ModelSelect2MultipleWidget(
					model = District,
					search_fields = ['district__icontains'],
					dependent_fields = {'state' : 'state'},
					max_results = 100,
				)
		)

My models look like this ->

    class State(models.Model):
	state = models.CharField(max_length = 1000)

	def __unicode__(self):
		return '%s' % (str(self.state))

class District(models.Model):
	state = models.ForeignKey(State)	
	district = models.CharField(max_length = 1000)

	def __unicode__(self):
		return '%s' % (str(self.district))

I call the form fields inside templates using {{ nationalFilter.state }} and {{ nationalFilter.district }} If I were to retain the commented code then they would work like any unchained fields do but when I remove them it says that the ‘Results could not be loaded’. I am trying to render form in the modal. The error it gives on the django command line server is the following

    Not Found: /select2/fields/auto.json
[09/Aug/2017 20:25:59] "GET /select2/fields/auto.json?term=&field_id=MTM5OTk5OTQ0NTg2NjQw%3A1dfSNx%3AvpS6GwaTyvV6gXAY-06cQSJyEFg HTTP/1.1" 404 1828

The error to me seems to be related to the url configuration. So I am adding that too here. My main urls.py(the one created by default) looks like this ->

   urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('data_analyser.urls')),
    url(r'^select2/', include('django_select2.urls')),
    url(r'^chaining/', include('smart_selects.urls')),
]

The other one that I created for my app looks like this ->

  urlpatterns = [
   url(r'^main$', views.main, name = 'main'),
   url(r'^select2/', include('django_select2.urls')),
]

Could you guys tell If I am doing anything wrong.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
cvipulcommented, May 25, 2019

Thanks @codingjoe

I implemented the Multi-Select Dependency widget as below, if someone needs it

class DependentMultipleSelectWidget(ModelSelect2MultipleWidget):
    def filter_queryset(self, request, term, queryset=None, **dependent_fields):
        # The super code ignores the dependent fields with multiple values
        dependent_fields_multi_value = {}
        for form_field_name, model_field_name in self.dependent_fields.items():
            if form_field_name+"[]" in request.GET and request.GET.get(form_field_name+"[]", "") != "":
                value_list = request.GET.getlist(form_field_name+"[]")
                dependent_fields_multi_value[model_field_name] = value_list

        if queryset is None:
            queryset = self.get_queryset()
        search_fields = self.get_search_fields()
        select = Q()
        term = term.replace('\t', ' ')
        term = term.replace('\n', ' ')
        for t in [t for t in term.split(' ') if not t == '']:
            select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields,
                             Q(**{search_fields[0]: t}))
        # TODO - Q doesnt support list of values, will have to add something of our own
        if dependent_fields:
            select &= Q(**dependent_fields)
        if dependent_fields_multi_value:
            queryset = queryset.filter(**dependent_fields_multi_value)

        return queryset.filter(select).distinct()

I am essentially using “[]” suffix at the end of request params to identify variables sending a list. Also, had to use direct “filter” method instead of a “Q” method in the queryset.

0reactions
miguelcleoncommented, Feb 3, 2021

For the #TODO I did: if dependent_fields_multi_value: for key,val in dependent_fields_multi_value.items(): select &= Q(**{“%s__in” % key: val})

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependent field does not work as expected on task "Assigned ...
When a reference field against the [sys_user] table (for example Assigned to) is dependent on another reference field against the [sys_user_group] table ...
Read more >
Dependent Field is not working pr - BMC Community
I have two dependent field on a single field called Platform. When i select any value from the Platform only one field(Customer) will...
Read more >
PI93803: DEPENDENT FIELDS DO NOT WORK IF ... - IBM
When resetting a BE Selector field's value, the JavaScript was trying to interpret the value as JSON. This reset function is called both...
Read more >
Issues for Dependent Fields | Drupal.org
Title Status Priority Category Version Co... "Hide if empty" option Active Normal Feature request 1.0.1 Mi... Support for Autocomplete fields Needs review Normal Feature request...
Read more >
Picklist Dependent fields -- the dependent field I want is not ...
As far as I know there are a few cases where a picklist cannot be a dependent field. Standard picklist fields cannot be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found