Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're going to want to make these actual models, so you'd have something like this:</p> <pre><code>class ProgrammingCategory(models.Model): name = models.CharField(max_length=200) class ProgrammingLanguage(models.Model): category = models.ForeignKey(ProgrammingCategory, related_name='languages') name = models.CharField(max_length=300) class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) planguages = models.ManyToManyField(ProgrammingLanguage) </code></pre> <p>Not only is this better from a maintainability standpoint (programming languages do change: new ones come around, old ones die out), but it also gives you much greater flexibility in querying.</p> <p>Then, you simply add a field to your <code>ModelForm</code> for the categories:</p> <pre><code>class UserProfileForm(forms.ModelForm): ... category = forms.ModelChoiceField(queryset=ProgrammingCategory.objects.all(), required=False) </code></pre> <p>And, in your form, you'll end up with a select with a complete list of categories and another with a complete list of languages. Then, all you need is some AJAX to do the filtering for you:</p> <p><strong>views.py</strong></p> <pre><code>from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest def ajax_get_languages_for_category(request): cat_id = request.GET.get('cat_id') if cat_id is not None: category = get_object_or_404(ProgrammingCategory, id=cat_id) data = serializers.serialize('json', category.languages.all()) return HttpResponse(data, mimetype='application/json') else: return HttpResponseBadRequest() </code></pre> <p><strong>script.js</strong></p> <pre><code>$(document).ready(function(){ var $category = $('#id_category'); function updateLanguageChoices() { var selected = $category.val(); if (selected) { $.getJSON('/path/to/ajax/view/', { cat_id: selected }, function (data, jqXHR) { var output = []; $.each(data, function(i, item){ output.append('&lt;option value="'+item.id+'"&gt;'+item.name+'&lt;/option&gt;'); }); $('#id_planguage').html(output.join('')); }); } } updateLanguageChoices(); $category.change(updateLanguageChoices); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload