четвер, 23 вересня 2010 р.

js dynamic select with django

If you will need dynamic change of your select in your django templates than follow this post. There are 3 models: ItemType, SubItemType (this select depends from ItemType), Category(depends from SubItemType) and model Item with foreign key to those 3 ones.


models.py

class ItemType(models.Model):
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description

class SubItemType(models.Model):
    parent_itemtype = models.ForeignKey(ItemType, verbose_name="Parent type")
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description

class Category(models.Model):
    parent_subitemtype = models.ForeignKey(SubItemType, verbose_name="Parent SubType")
    description = models.CharField(max_length=128, null=False, default='', verbose_name="Description")

    def __unicode__(self):
        return self.description


class Item(models.Model):
    type = models.ForeignKey(ItemType, verbose_name="Type", null=True)
    other_type = models.CharField(max_length=128, null=True, verbose_name="Other type")

    sub_type = models.ForeignKey(SubItemType, verbose_name="Subtype", null=True)
    other_sub_type = models.CharField(max_length=128, null=True, verbose_name="Other subtype")

    category = models.ForeignKey(Category, verbose_name="Category", null=True)
    other_category = models.CharField(max_length=128, null=False, default='', verbose_name="Other category")


Usually we used something like this:


class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
but when we need some widgets(RadioButton etc) or when we need to specify some attributes for js(like "onchange", "style" etc) - we need to rewrite some fields of our model in forms.py as follows.
forms.py

class ItemForm(forms.ModelForm):   
    ITEM_TYPE_CHOICES = [('', 'others'), ] + [(str(t.id), t.description) for t in ItemType.objects.all()]
    SUB_ITEM_TYPE_CHOICES = [('', 'others), ] + [(t.id, t.description) for t in SubItemType.objects.all()]
    CATEGORY_TYPE_CHOICES = [('', 'others'), ] + [(t.id, t.description) for t in Category.objects.all()]
    type = forms.ChoiceField(label="Type", required=False,
            choices=ITEM_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'loadSubType(this);'}))

    sub_type = forms.ChoiceField(label="Subtype", required=False,
            choices=SUB_ITEM_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'loadCategory(this);'}))

    category = forms.ChoiceField(label="Category", required=False,
            choices=CATEGORY_TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'showHideOtherCategory(this);'}))
    other_type = forms.CharField(label="", max_length=128, required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))
    other_sub_type = forms.CharField(label="", max_length=128,     required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))
    other_category = forms.CharField(label="", max_length=128, required=False, widget=forms.TextInput(attrs={'style':'display:block;'}))

    class Meta:
        model = Item

    def clean_type(self):
        codice = self.data["type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return ItemType.objects.get(id=codice)
            except ItemType.DoesNotExist:
                raise ValidationError("Type %s doesn't exist" %codice)

    def clean_sub_type(self):
        codice = self.data["sub_type"]
        codice2 = self.data["type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return SubItemType.objects.get(id=codice, parent_itemtype=codice2)
            except SubItemType.DoesNotExist:
                raise ValidationError("SubType doesn't exist or doesn't fit Type selected above")

    def clean_category(self):
        codice = self.data["category"]
        codice2 = self.data["sub_type"]
        num_words=len(codice.split())
        if num_words!=0:
            try:
                return Category.objects.get(id=codice, parent_subitemtype=codice2)
            except Category.DoesNotExist:
                raise ValidationError("Category doesn't exist or doesn't fit SubType selected above")
functions clean_* are used for good-view django error validation.


In views.py there are some views used by our js-script for inserting in html < select > tags. We select needed data to dictionary var and then using simplejson we create json data and return it to our js-script.

views.py

def get_json_subtype(request, id):
    subitems=SubItemType.objects.filter(parent_itemtype=id)
    var={}
    temp1=""
    for s in subitems:
        temp1+=str(s.id)+" : '"+s.description+"', "
    var[id]="{"+temp1+"}"
    js_data = simplejson.dumps(var, ensure_ascii=False)
    # replacement of unnecessary characters
    # mb not so correct but it works for me
    js_data=js_data.replace('"{','{').replace('}"','}').replace(', }',' }');
    mimetype = 'application/javascript'
    return HttpResponse(js_data,mimetype)

def get_json_category(request, id):
    categories=Category.objects.filter(parent_subitemtype=id)
    var={}
    temp1=""
    for c in categories:
        temp1+=str(c.id)+" : '"+c.description+"', "
    var[id]="{"+temp1+"}"
    js_data = simplejson.dumps(var, ensure_ascii=False)
    js_data=js_data.replace('"{','{').replace('}"','}').replace(', }',' }');
    mimetype = 'application/javascript'
    return HttpResponse(js_data,mimetype)

Of course you can make one more universal function, instead of these two.

Then create some js-file in your media dir and put this code there.

function loadSubType(objSelect)
  {
      if(objSelect[objSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_type").style.display = "block";
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_sub_type").length=1;
          document.getElementById("id_category").length=1;
       }
      else
      {
          document.getElementById("id_other_type").style.display = "none";
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_other_type").value = "";

          var url="/get-json-subtype/"+objSelect[objSelect.selectedIndex].value;
          loadJsonData(objSelect, url, "id_sub_type");
       
      }
  }

function loadCategory(objectSelect)
  {
      if(objectSelect[objectSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_sub_type").style.display = "block";
          document.getElementById("id_category").length=1;
       }
      else
      {
          document.getElementById("id_other_sub_type").style.display = "none";
          document.getElementById("id_other_sub_type").value = "";

          var url="/get-json-category/"+objectSelect[objectSelect.selectedIndex].value;
          loadJsonData(objectSelect, url, "id_category");
      }
  }

function showHideOtherCategory(objSelect)
  {
      if(objSelect[objSelect.selectedIndex].text ==  "others")
       {
          document.getElementById("id_other_category").style.display = "block";
       }
    else
      {
          document.getElementById("id_other_category").style.display = "none";
          document.getElementById("id_other_category").value = "";
      }
  }

include this js-script to your template
<script type="text/javascript" src="/your_media_dir/your_script.js"></script>.

and finally your urls.py should include this:

    (r'^get-json-subtype/(\d+)/$', get_json_subtype),
    (r'^get-json-category/(\d+)/$', get_json_category),

Now when you choose some value from ItemType js-script will load values that you need to SubItemType select, and when you choose some value in SubItemType js will load values to Category select. And when you'll choose "others" in select box - an additional input field will appear under your select.

Немає коментарів:

Дописати коментар