Login

Select or Create widget

Author:
Naster
Posted:
February 28, 2014
Language:
Python
Version:
1.6
Score:
0 (after 0 ratings)

This widget is based on django foreign key form field, but its completely dynamic.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class SelectOrCreate(Select):
    """
    Base class for all <select> widgets with chosen js.
    """
    def __init__(self, form, url, attrs=None, choices=(), ):
      super(SelectOrCreate, self).__init__(attrs, choices)
      self.form = form
      self.url = url

    def render(self, name, value, attrs=None, choices=()):
      output = [super(SelectOrCreate, self).render(name, value, attrs, choices), ]
      final_attrs = self.build_attrs(attrs, name=name)
      ret = {'final_attrs': final_attrs,
             'STATIC_URL': settings.STATIC_URL,
             'id': final_attrs['id'],
             'form': self.form,
             'redirect_url': self.url}
      output.append(mark_safe(render_to_string('selectorcreatewidget.html', ret)))
      return mark_safe('\n'.join(output))




selectorcreatewidget.html:

<a href="#" name="add_dialog" data-id="{{ id }}">
  <img width="10" height="10" alt="Add Another"
       src="{{ STATIC_URL }}admin/img/icon_addlink.gif" />
</a>

<div id="{{ id }}-dialog" style="display: none;" title="Add Another">
    {% csrf_token %}
    <div id="form-dialog">
      {{ form.as_p }}
    </div>
    <p><input type="submit" value="Add" name="add_another_{{ id }}"
              data-url="{% url redirect_url %}"/></p>
</div>



example.js 
// Generated by CoffeeScript 1.7.1
$(function() {
  $('a[name=add_dialog]').click(function() {
    var dialog, id;
    id = $(this).data('id');
    dialog = $('#' + id + '-dialog').dialog();
    return false;
  });
  return $('input[name=add_another_id_series]').click(function() {
    var data, form;
    form = $(this).parent().parent().find('#form-dialog');
    data = {
      param1: $('#param1').val(),
      param2: $('#param2').val(),
      param3: $('#param3').val(),
      param4: $('#param4').val(),
      param5: $('#param5').val()
    };
    return $.ajax($(this).data('url'), {
      type: 'POST',
      beforeSend: function(request) {
        request.setRequestHeader('Cache-Control', 'no-cache');
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        return request.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
      },
      data: data,
      success: function(data) {
        if (data.status === 'Wrong') {
          $(form).html(data.form);
        }
        if (data.status === 'Ok') {
          $('#id_series').append('<option value="' + data.id + '">' + data.name + '</option>');
          $('#id_series').val(data.id);
          $('#id_series-dialog').dialog('close');
        }
      }
    });
  });
});

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.