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.

ChainedManyToManyField not deploy select options in relation to parent field. In django admin works.

See original GitHub issue

Checklist

Put an x in the bracket when you have completed each task, like this: [x]

  • This issue is not about installing previous versions of django-smart-selects older than 1.2.8. I understand that previous versions are insecure and will not receive any support whatsoever.

  • I have verified that that issue exists against the master branch of django-smart-selects.

  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate. There is some similar issues, but I cannot setup if them are duplicate. For this reason, I don’t check here the option despite I’ve searched. My apologies just in case

This issue is similar, but in their case, happens the same problem to me but in the admin area. My problem is in my frontend application using forms.ModelForm

  • I have debugged the issue to the smart_selects app. In my command line interface, I cannot view the http requests events in relation to my issue. I know how to use some things like ipdb, but unknow how to use in this situation due to django-smart-selects work internally in this chaining scenario

  • I have reduced the issue to the simplest possible case. Yes, I guess that below in my description, the issue is enoughly clear

  • I have included all relevant sections of models.py, forms.py, and views.py with problems.

  • I have used GitHub Flavored Markdown to style all of my posted code.

Steps to reproduce

1. My models

I have the following models: In StudiesTypeOffered model I have some type of studies, in the field name.

class StudiesTypeOffered(models.Model):

    CONTINUING_EDUCATION_STUDIES = 'Continuing Education studies'
    TECHNIQUE = 'Technique'
    TECHNOLOGY = 'Technology'
    PROFESSIONAL = 'Professional'
    SPECIALIZATION = 'Specialization'
    MASTER = 'Master'
    DOCTORATE = 'Doctorate'

    STUDIES_TYPE_CHOICES = (
        (CONTINUING_EDUCATION_STUDIES, u'Continuing Education studies'),
        (TECHNIQUE, u'Technique'),
        (TECHNOLOGY, u'Technology'),
        (PROFESSIONAL, u'Professional'),
        (SPECIALIZATION, u'Specialization'),
        (MASTER, u'Master'),
        (DOCTORATE, u'Doctorate'),
    )

    name = models.CharField(
        max_length=100,
        choices=STUDIES_TYPE_CHOICES,
        blank=False,
        verbose_name=u'nombre',
    )

    class Meta:
        verbose_name = "Tipo de estudio ofertado"
        verbose_name_plural = "Tipo de estudios ofertados"

    def __str__(self):
        return "%s" % self.name

And I have the StudiesOffertList model, which have an studies offert list asociated to studies type in my parent model above

class StudiesOffertList(models.Model):

    name = models.CharField(
        max_length=100,
        verbose_name = u'nombre'
    )

    studies_type_offered_associated = models.ManyToManyField(
        StudiesTypeOffered,
        blank=True,
        verbose_name='Tipo de oferta asociada'
    )

    class Meta:
        verbose_name = "Oferta de estudios"
        verbose_name_plural = "Oferta de estudios"

    def __str__(self):
        return "%s" % self.name

In my StudyHostProfile model. which is the model that meet to previous models, I have:

studies_type_offered is my parent field studies_offert_list is my child field

class StudyHostProfile(models.Model):

    studies_type_offered = models.ManyToManyField(
        'StudiesTypeOffered',
        verbose_name=u'Studies Type offered'
    )

    studies_offert_list = ChainedManyToManyField(
        'StudiesOffertList', # Chained model
        horizontal=False,
        verbose_name='Studies Offert List',
        chained_field='studies_type_offered',
        chained_model_field='studies_type_offered_associated',
    )

2. My forms.py file

I am rendering the following field in my forms.py

class StudyHostProfileForm(forms.ModelForm):
    title = "Study Host Details"
    widgets = {
            'institute_character':forms.RadioSelect,
    }

    high_quality_accreditations = forms.MultipleChoiceField(
        required=False,
        label='Accreditations of high quality',
        widget=CheckboxSelectMultiple(),
        choices=StudyHostProfile.ACCREDITATIONS_CHOICES,
    )

    rankings_classification = forms.CharField(widget=forms.Textarea)
    knowledge_topics_choice = forms.CharField(widget=forms.Textarea)
    strengths = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = StudyHostProfile
        fields = ('institution_type', 'institute_character',
            'high_quality_accreditations', 'students_number',
            'rankings_classification', 'knowledge_topics_choice',
            'strengths', 'studies_type_offered', 'studies_offert_list',)

3. My views.py

@login_required
def user_profile_update_view(request, slug):
    user = request.user

    # Populate the forms and Instances (if applicable)
    form_profiles = []
    if user.is_study_host:
        profile = user.get_study_host_profile()
        form_profiles.append({'form': StudyHostProfileForm, 'instance': user.studyhostprofile, 'title': "Study Host Details"})

    if request.method == 'POST':
        forms = [x['form'](data=request.POST, instance=x['instance'],) for x in form_profiles]
        if all([form.is_valid() for form in forms]):
            for form in forms:
                form.save()
            return redirect('dashboard')
    else:
        forms = [x['form'](instance=x['instance']) for x in form_profiles]

    return render(request, 'accounts/profile_form.html', {'forms': forms, 'userprofile':profile,})

**4. My profile_form.html template

{% extends 'layout.html' %}
{% load bootstrap3 %}
{% block title_tag %}Accounts | Profile | iHost {{ block.super }}{% endblock %}
{% block body_content %}
<div class="container">  
    <form method="POST">
        {% csrf_token %}
        {% for form in forms %}
            <h2>{{ form.title }}</h2>
                {% bootstrap_form form %}
        {% endfor %}
        <input type="submit" value="Save Changes" class="btn btn-default">
    </form>
</div>
{% endblock %}

In my urls.py I have this

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

Actual behavior

In my frontend application the current behavior is:

gifrecord_2017-06-07_111419

In my django-console do not happen any http GET requests

Expected behavior

The expected behavior is when I choose some option in my studies_type_offered parent field, in the studies_offert_list child field appear some options according to the previous selection.

Curiously in my admin section in Django, this expected behavior is accomplished. Worrks Ok

gifrecord_2017-06-07_112432

This is the traceback http requests in my django console

[07/Jun/2017 16:25:07] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/6/ HTTP/1.1" 200 86
[07/Jun/2017 16:25:08] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/6,7/ HTTP/1.1" 200 136
[07/Jun/2017 16:25:09] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/4,6,7/ HTTP/1.1" 200 267
[07/Jun/2017 16:25:09] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/3,4,6,7/ HTTP/1.1" 200 311
[07/Jun/2017 16:25:09] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/2,3,4,6,7/ HTTP/1.1" 200 311
[07/Jun/2017 16:25:10] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/1,2,3,4,6,7/ HTTP/1.1" 200 396
[07/Jun/2017 16:25:12] "GET /chaining/filter/accounts/StudiesOffertList/studies_type_offered_associated/accounts/StudyHostProfile/studies_offert_list/1,2,3,4,5,6,7/ HTTP/1.1" 200 489

Why the chaining works in django admin and in my django frontend application does not works? In a previous opportunity I can made this using django-smart-selects==1.2.2 which currently is unsupported.

My current packages are:

Django==1.11.1
django-smart-selects==1.5.2

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
blagcommented, Jun 11, 2017

A few questions:

  • Is the form_profiles template context variable what you expect it to be?
  • Is your browser loading /static/smart-selects/admin/js/bindfields.js on your problematic page?
  • Is your browser loading /static/smart-selects/admin/js/bindfields.js on your admin page?
  • Are there any HTTP requests in your browser console (not the Django console) in the problematic page?
  • Is your form being used as an inline form of a formset? It doesn’t look like it from the view you posted, but I just wanted to double check.

I suspect that your problematic page is not loading the bindfields.js file (probably due to a bug in django-smart-selects), which is causing the form to not be initialized for smart selecting.

If you manually include these three pieces of JS in your template with <script src=""> tags (in this order):

  • /static/smart-selects/admin/js/chainedfk.js
  • /static/smart-selects/admin/js/chainedm2m.js
  • /static/smart-selects/admin/js/bindfields.js

does your problematic page work properly?

0reactions
manelcloscommented, Aug 18, 2020

Closing due to inactivity.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to apply DEBUG to the django admin forms fields?
Just by briefly looking to your video and the code of "django-smart-select" application, I can see that this application was not meant to...
Read more >
django-smart-selects: ChainedManyToManyField value not ...
I am working with django-smart-selects via django admin form. The idea that I have is try a model chaining or deployment of value...
Read more >
The Django admin site
By default, Django's admin uses a select-box interface (<select>) for fields that are ForeignKey or have choices set. If a field is present...
Read more >
Django admin integration
The polymorphic admin interface works in a simple way: ... The polymorphic admin is implemented via a parent admin that redirects the edit...
Read more >
Dependent & Searchable Selections in Django Model Admin ...
Dependent & Searchable Selections in Django Model Admin is now a cakewalk · A select field can derive one or more select fields(One...
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