views:

274

answers:

2

I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. I am sending a hash to a template that contains the following values

{'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.844032999999996, u'place': u'1053 Bowring Cres, Milton, ON L9T, CA', u'description': u'Home base'}, {u'lat': 43.730550000000001, u'lng': -79.805334000000002, u'place': u'50 Dawnridge Trl, Brampton, ON L6Z, CA', u'description': u'Southfork'}]}

I then pass this data to my template and I need to do the following:

  • create a form
  • pre-populate a number of form fields related to the values inside 'locations'
  • if I have less than 5 'locations' add in a number of blank form fields until I have 5

Here's the code that pulls in and generates the data -- it grabs info from CouchDB

 def get_by_id(self, username, search_id):
      if username and search_id:
          info = db.get(search_id)

          if info['user'] == username:
              return {'date': info['date'],
                      'locations': json.loads(info['locations'])}

I suppose I could somehow manipulate what is in info['locations'] to add in an ID, but I've been struggling with understanding how Python handles iterating through the JSON.

Here's the code in template I'm using to create the form. my_search contains the data I've shown above

<form method="post" action="/locations">
<input type="hidden" name="search_id" value="{{ search_id }}">
    <table>
        <tr>
            <th>Location</th>
            <th>Description</th>
        </tr>
        {% for location in my_search.locations %}
        <tr>
            <td><input type="text" name="location" id="id_location"
                       value="{{ location.place }}"></td>
            <td><input type="text" name="description" id="id_description"
                       value="{{ location.description }}"></td>
        </tr>
        {% endfor %}
     </table>
     <input type="submit" value="Update Plan">
  </form>

Thoughts on how to (a) easily add in a unique ID and (b) add in the missing blank form field pairs if I have less than 5 locations would be greatly appreciated.

+2  A: 
if info['user'] == username:
  locations = (json.loads(info['locations']) +
    [{'place': '', 'description': ''}] * 5)[:5]

  return {'date': info['date'], 'locations': locations}
Ignacio Vazquez-Abrams
Am I correct in assuming that the [:5] part says "do this until we have 5 elements in the array" ?
GrumpyCanuck
It means "give me up to the fifth element of the sequence". http://docs.python.org/tutorial/introduction.html#lists
Ignacio Vazquez-Abrams
+2  A: 

(a)

id="id_location_{{ forloop.counter }}"
Ofri Raviv
This worked perfectly as well.
GrumpyCanuck