Need Help Getting Linked Selects to Work

21 views
Skip to first unread message

Mark Phillips

unread,
Jan 26, 2018, 5:41:29 PM1/26/18
to yourlabs
I am trying to add a linked select box in the admin section of my django app. 

What works - I can access the autocomplete view that generates the data for the linked select from a browser. I can access my django admin site.

What does not work - (1) the reverse url test from the django shell, and (2) the linked select box is not populated with any values when I select a value in the first select box. 

I think I have a url issue because when I make a selection in the first select box, I don't see the print statement I embedded in the view saying it was called. I see the print statement in the console when I access the url from the browser directly.

My models in models.py:
class MetaData(models.Model):
    metadata_id = models.AutoField(primary_key = True)
    name = models.CharField('metadata name', max_length=200, unique=True)
    description = models.TextField('description')

    def __str__(self):
        return "%s" % (self.name)
                   
class MetaDataValue(models.Model):
    metadata_id = models.ForeignKey(MetaData, on_delete=models.CASCADE,)
    value = models.CharField('value', max_length=200, unique=True)
    
    def __str__(self):
        return self.value
      
class DocumentMetaDataValue(models.Model):
    document = models.ForeignKey(Document, on_delete=models.CASCADE)
    metadata = models.ForeignKey(MetaData, on_delete=models.CASCADE)
    metadataValue = models.ForeignKey(MetaDataValue, on_delete=models.CASCADE) 
    
    def __str__(self):
        return '{}: {} {}'.format(self.document, self.metadata, self.metadataValue)

My view in views.py
class MetaDataValueAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        
        print ("I am MetaDataValueAutocomplete.get_query!!")
        
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated():
            return MetaDataValue.objects.none()

        qs1 = MetaData.objects.all()
        qs = MetaDataValue.objects.all()

        if self.q:
            qs = qs.filter(metadata_id = qs1.filter(name=self.q)).order_by("value")

        return qs

My urls.py (project level, not app level)
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^metadatavalue-autocomplete/$', MetaDataValueAutocomplete.as_view(), name='metadatavalue-autocomplete', ),
    url(r'^memorabilia/', include('memorabilia.urls', namespace = 'memorabilia')),
    url(r'^accounts/', include('django.contrib.auth.urls')),
    url(r'^$', generic.RedirectView.as_view(url='/workflow/', permanent=False)),
    url(r'', include(frontend_urls)),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

    #urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Output from browser window testing the metadatavalue-autocomplete url:
http://localhost:8099/metadatavalue-autocomplete/?q=Meal

{"pagination": {"more": false}, "results": [{"text": "Breakfast", "id": "137"}, {"text": "Dinner", "id": "138"}, {"text": "High Tea", "id": "139"}, {"text": "Lunch", "id": "140"}, {"text": "Snack", "id": "141"}]}


Output from reverse url
>>> reverse('metadatavalue-autocomplete') Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/django/urls/resolvers.py", line 438, in _reverse_with_prefix possibilities = self.reverse_dict.getlist(lookup_view) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/django/urls/resolvers.py", line 335, in reverse_dict return self._reverse_dict[language_code] KeyError: None >>>
My admin.py:
class DocumentMetaDataValueForm(forms.ModelForm): metadataValue = forms.ModelChoiceField( queryset = MetaDataValue.objects.all(), widget = autocomplete.ModelSelect2(url='metadatavalue-autocomplete') ) class Meta: model = DocumentMetaDataValue fields = '__all__'

class DocumentMetaDataValueAdmin(admin.ModelAdmin): form = DocumentMetaDataValueForm

admin.site.register(DocumentMetaDataValue,DocumentMetaDataValueAdmin)

Any ideas on what I am missing - I am stumped and seem to have exhausted the info in the test projects for django-autoselect-light.

Thanks!

Mark







Jamesie Pic

unread,
Jan 26, 2018, 6:42:59 PM1/26/18
to yourlabs
Hi Mark

Is it possible to publish this code on a git repository and let us know what python, django and dal versions you are using ?

I find interesting that language_code appears to be used in the traceback, is i18n urls disabled ?

Did you try in the shell importing urlpatterns from settings.ROOT_URLCONF and check that the URL is properly defined in there ?

Thanks

Jamesie Pic

unread,
Jan 26, 2018, 6:44:39 PM1/26/18
to yourlabs
Also, what is the widget output HTML like and is the proper url in it ?

Also is the widget making any request at all when you type in it ?
--

Mark Phillips

unread,
Jan 26, 2018, 7:01:14 PM1/26/18
to django-autoselect-light
Jamesis,

The code I uploaded are just the salient fragments for the linked selects from a bigger project. I am not sure I want to publish the entire project.

To answer some of your questions - 

python version is 3.4.3
django is 1.11.2

Not sure how to find the dal version, but I am pretty sure it is 3.2.10. I did a pip install yesterday.

Can you give me a little more instruction on the "...importing urlpatterns from settings.ROOT_URLCONF and check that the URL is properly defined in there?"

Just a django newbie!

Thanks!,

Mark

--
You received this message because you are subscribed to the Google Groups "yourlabs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to yourlabs+unsubscribe@googlegroups.com.
To post to this group, send email to your...@googlegroups.com.
Visit this group at https://groups.google.com/group/yourlabs.
To view this discussion on the web visit https://groups.google.com/d/msgid/yourlabs/CAC6Op1_ncj%2B19%2B7yZ4fruuc8qZy4J%2BOdQrNr_kQ__Em86z6t%2Bg%40mail.gmail.com.

For more options, visit https://groups.google.com/d/optout.

Mark Phillips

unread,
Jan 26, 2018, 7:11:28 PM1/26/18
to django-autoselect-light
Jamesis,

There is nothing in the console output that makes me think the widget is posting a request to the server. As I said previously, I put a print statement in the view and that is not firing. I don't see any url in the console output that has the text 'metadatavalue-autocomplete' in it. 

As for the HTML output, here it is for the two linked select boxes.

        <div class="form-row field-metadata">
                <div>
                        <label class="required" for="id_metadata">Metadata:</label>
                            <div class="related-widget-wrapper">
    <select name="metadata" required id="id_metadata">
  <option value="" selected>---------</option>

  <option value="1">Address</option>

  <option value="4">Date</option>

  <option value="5">Decade</option>

  <option value="27">Description</option>

  <option value="7">Event</option>

  <option value="2">Formal Dance Type</option>

  <option value="9">Holiday</option>

  <option value="12">Location</option>

  <option value="13">Meal</option>

  <option value="18">Orientation</option>

  <option value="15">Person</option>

  <option value="16">Pet Names</option>

  <option value="17">Pets</option>

  <option value="22">Photo Type</option>

  <option value="20">School</option>

  <option value="21">Sports</option>

  <option value="28">Title</option>

  <option value="23">Type of School</option>

</select>
    
        <a class="related-widget-wrapper-link change-related" id="change_id_metadata"
            data-href-template="/admin/memorabilia/metadata/__fk__/change/?_to_field=metadata_id&amp;_popup=1"
            title="Change selected meta data"><img src="/static/admin/img/icon-changelink.svg" alt="Change"/></a><a class="related-widget-wrapper-link add-related" id="add_id_metadata"
            href="/admin/memorabilia/metadata/add/?_to_field=metadata_id&amp;_popup=1"
            title="Add another meta data"><img src="/static/admin/img/icon-addlink.svg" alt="Add"/></a>
    
</div>           
                </div>
            
        </div>
    
        <div class="form-row field-metadataValue">
                <div>
                        <label class="required" for="id_metadataValue">Metadatavalue:</label>
                        
                            <select name="metadataValue" data-autocomplete-light-function="select2" required id="id_metadataValue" data-autocomplete-light-url="/metadatavalue-autocomplete/">
  <option value="" selected>---------</option>

</select>
                        
I looked at this page source after I selected Meal from the first select box. However, the source does not show that Meal is selected, and consequently, the url for the second select box does not have the parameter Meal in the url. Is this correct behavior?

Thanks!

Mark

--
You received this message because you are subscribed to the Google Groups "yourlabs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to yourlabs+unsubscribe@googlegroups.com.
To post to this group, send email to your...@googlegroups.com.
Visit this group at https://groups.google.com/group/yourlabs.
Reply all
Reply to author
Forward
0 new messages