Below the Radar
Below the Radar

Reputation: 7635

Django - Dynamic ChoiceField - All images in static dir

I would like to create an app that will allow the user to choose an image between all those contained into a specific folder. The dropdown input would render a thumbnail of the image and the filename. The choice value would be the path of the image.

I know it could be possible to do it with jQuery UI and javascript, but I would like to know how I could generate the choices dynamically in the form in order to get the visual effect needed.

If you have other ideas, thank you for any suggestion

dynamic form (not complete):

filename_list = ???
path_list = ???
images_thumbnails_list = ???

class imagesForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(imagesForm, self).__init__(*args, **kwargs)
        self.fields['selectedImage'] = forms.ChoiceField(choices=
                         for path in path_list: str(path),
                         for filename in filename_list: str(filename)
                         for thumbnail in images_thumbnails_list: thumbnail )

example of input field needed:

  <select name="webmenu" id="webmenu">
    <option value="calendar" data-image="icons/icon_calendar.gif">Calendar</option>
    <option value="shopping_cart" data-image="icons/icon_cart.gif">Shopping Cart</option>
    <option value="cd" data-image="icons/icon_cd.gif">CD</option>
    <option value="email"  selected="selected" title="icons/icon_email.gif">Email</option>
    <option value="faq" data-image="icons/icon_faq.gif">FAQ</option>
    <option value="games" data-image="icons/icon_games.gif">Games</option>
  </select>

visual example:

enter image description here

Upvotes: 3

Views: 3155

Answers (1)

amdorra
amdorra

Reputation: 1556

I think a good solution for this task would be making a model for you choices

class Countries(models.Model):
    name = models.CharField(length=255)
    thumbnail = models.ImageField(upload_to='static_directory')

and use fixtures to populate those data

countries_list = Countries.objects.all()

class imagesForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(imagesForm, self).__init__(*args, **kwargs)
        self.fields['selectedImage'] = forms.ChoiceField(choices=countries_list)

and render them in your templates like this

{% for country in field.choices %}
    <option value="{{country.id}}"><img src="{{country.image.url}}"/> {{country.name}}</option>
{% endfor %}

Upvotes: 2

Related Questions