开发者

Dynamic form field generation in Django templates

开发者 https://www.devze.com 2022-12-16 04:48 出处:网络
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

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 t开发者_如何学编程ype="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.


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

  return {'date': info['date'], 'locations': locations}


(a)

id="id_location_{{ forloop.counter }}"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号