Higure
Higure

Reputation: 235

Create a dynamic search form in Django

in my Django 1.5 model I'm trying to create a form that let me book a place in a study room.

The study room is defined as follows in models.py:

class StudyRoom(models.Model):
    name = models.CharField(max_length = 30, primary_key = True)
    city = models.CharField(max_length = 30)
    placesno = models.IntegerField()

    def __unicode__(self):
        return self.name

and this is the relative form:

class SearchSeat(forms.Form):
    morning = 'AM'
    evening = 'PM'

    daysection_choices = ((morning, 'Morning'), (evening, 'Evening'),)

    city = forms.ChoiceField(choices = [], required=True, label='Select a city?')
    study_room = forms.ChoiceField(choices = [], required=True, label='Select a study room?')
    day = forms.DateField(label = 'Select a day', required=True, widget=forms.extras.SelectDateWidget(years=range(2014, 2015)))
    section = forms.ChoiceField(choices=daysection_choices, label = 'Morning (form 8.00 to 13.00) or evening (from 13.00 to 18..)?')

    def __init__(self, *args, **kwargs):
    super(SearchSeat, self).__init__(*args, **kwargs)
    self.fields['city'].choices = StudyRoom.objects.all().values_list("city","city").distinct()
    search_city = self.fields['city']
    self.fields['study_room'].choices = StudyRoom.objects.filter(city = search_city).values_list("name")

The objective was to let the user select the city and then filter the study room and show only the ones in the selected city, all in one form without changing page.

The code written like this doesn't work and I'm starting to think that there isn't a solution without using client side side scripting (it's a Django+Python project so we are supposed to use only those two instruments).

Upvotes: 0

Views: 1875

Answers (1)

ProfHase85
ProfHase85

Reputation: 12233

For your problem there can only be a solution with client scripting:

At the moment the html is created, the study-room choices are not determined. This means that on city change, you will need to manipulate your html, which means client side programming like:

$(document).ready(function(){
    $('#id_city').on('change', function(){
...
})
);

There is no need for an ajax request, though: you could save the choices into a 'data' attribute in your html and access it using: http://api.jquery.com/data/

You would need then to modify your fields:

self.fields['city'] = forms.Select(attrs={'data-london':'[json_dump of londondata], 'data-paris': '[json_dump of paris study rooms]' etc})

Depending on the amount of data, the ajax call would be a cleaner solution

Upvotes: 1

Related Questions