| Home | Trees | Indices | Help |
|---|
|
|
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2008-2009 Benoit Chesneau <benoitc@e-engura.com>
4 #
5 # Permission to use, copy, modify, and distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 #
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 #
17 # code heavily inspired from django.forms.models
18 # Copyright (c) Django Software Foundation and individual contributors.
19 # All rights reserved.
20 #
21 # Redistribution and use in source and binary forms, with or without modification,
22 # are permitted provided that the following conditions are met:
23 #
24 # 1. Redistributions of source code must retain the above copyright notice,
25 # this list of conditions and the following disclaimer.
26 #
27 # 2. Redistributions in binary form must reproduce the above copyright
28 # notice, this list of conditions and the following disclaimer in the
29 # documentation and/or other materials provided with the distribution.
30 #
31 # 3. Neither the name of Django nor the names of its contributors may be used
32 # to endorse or promote products derived from this software without
33 # specific prior written permission.
34 #
35 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
36 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
37 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
39 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
40 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
41 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
42 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
44 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45
46 """ Implement DocumentForm object. It map Document objects to Form and
47 works like ModelForm object :
48
49 >>> from couchdbkit.ext.django.forms import DocumentForm
50
51 # Create the form class.
52 >>> class ArticleForm(DocumentForm):
53 ... class Meta:
54 ... model = Article
55
56 # Creating a form to add an article.
57 >>> form = ArticleForm()
58
59 # Creating a form to change an existing article.
60 >>> article = Article.get(someid)
61 >>> form = ArticleForm(instance=article)
62
63
64 The generated Form class will have a form field for every model field.
65 Each document property has a corresponding default form field:
66
67 * StringProperty -> CharField,
68 * IntegerProperty -> IntegerField,
69 * DecimalProperty -> DecimalField,
70 * BooleanProperty -> BooleanField,
71 * FloatProperty -> FloatField,
72 * DateTimeProperty -> DateTimeField,
73 * DateProperty -> DateField,
74 * TimeProperty -> TimeField
75
76
77 More fields types will be supported soon.
78 """
79
80
81 from django.utils.text import capfirst
82 from django.utils.datastructures import SortedDict
83 from django.forms.util import ErrorList
84 from django.forms.forms import BaseForm, get_declared_fields
85 from django.forms import fields as f
86 from django.forms.widgets import media_property
87
88 FIELDS_PROPERTES_MAPPING = {
89 "StringProperty": f.CharField,
90 "IntegerProperty": f.IntegerField,
91 "DecimalProperty": f.DecimalField,
92 "BooleanProperty": f.BooleanField,
93 "FloatProperty": f.FloatField,
94 "DateTimeProperty": f.DateTimeField,
95 "DateProperty": f.DateField,
96 "TimeProperty": f.TimeField
97 }
98
100 """
101 Returns a dict containing the data in ``instance`` suitable for passing as
102 a Form's ``initial`` keyword argument.
103
104 ``properties`` is an optional list of properties names. If provided,
105 only the named properties will be included in the returned dict.
106
107 ``exclude`` is an optional list of properties names. If provided, the named
108 properties will be excluded from the returned dict, even if they are listed
109 in the ``properties`` argument.
110 """
111 # avoid a circular import
112 data = {}
113 for prop_name in instance._doc.keys():
114 if properties and not prop_name in properties:
115 continue
116 if exclude and prop_name in exclude:
117 continue
118 data[prop_name] = instance[prop_name]
119 return data
120
122 """
123 Returns a ``SortedDict`` containing form fields for the given document.
124
125 ``properties`` is an optional list of properties names. If provided,
126 only the named properties will be included in the returned properties.
127
128 ``exclude`` is an optional list of properties names. If provided, the named
129 properties will be excluded from the returned properties, even if
130 they are listed in the ``properties`` argument.
131 """
132 field_list = []
133
134 values = []
135 if properties:
136 values = [document._properties[prop] for prop in properties if \
137 prop in document._properties]
138 else:
139 values = document._properties.values()
140 values.sort(lambda a, b: cmp(a.creation_counter, b.creation_counter))
141
142 for prop in values:
143 if properties and not prop.name in properties:
144 continue
145 if exclude and prop.name in exclude:
146 continue
147 property_class_name = prop.__class__.__name__
148 if property_class_name in FIELDS_PROPERTES_MAPPING:
149 defaults = {
150 'required': prop.required,
151 'label': capfirst(prop.verbose_name),
152 }
153
154 if prop.default is not None:
155 defaults['initial'] = prop.default_value
156
157 if prop.choices:
158 if prop.default:
159 defaults['choices'] = prop.default_value() + list(
160 prop.choices)
161 defaults['coerce'] = prop.to_python
162
163 field_list.append((prop.name,
164 FIELDS_PROPERTES_MAPPING[property_class_name](**defaults)))
165 return SortedDict(field_list)
166
169 self.document = getattr(options, 'document', None)
170 self.properties = getattr(options, 'properties', None)
171 self.exclude = getattr(options, 'exclude', None)
172
175 try:
176 parents = [b for b in bases if issubclass(b, DocumentForm)]
177 except NameError:
178 # We are defining ModelForm itself.
179 parents = None
180
181 declared_fields = get_declared_fields(bases, attrs, False)
182 new_class = super(DocumentFormMetaClass, cls).__new__(cls, name, bases,
183 attrs)
184
185 if not parents:
186 return new_class
187
188 if 'media' not in attrs:
189 new_class.media = media_property(new_class)
190
191 opts = new_class._meta = DocumentFormOptions(getattr(new_class,
192 'Meta', None))
193
194 if opts.document:
195 # If a document is defined, extract form fields from it.
196 fields = fields_for_document(opts.document, opts.properties,
197 opts.exclude)
198 # Override default docuemnt fields with any custom declared ones
199 # (plus, include all the other declared fields).
200 fields.update(declared_fields)
201 else:
202 fields = declared_fields
203
204 new_class.declared_fields = declared_fields
205 new_class.base_fields = fields
206 return new_class
207
209 """ Base Document Form object """
210
211 - def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
212 initial=None, error_class=ErrorList, label_suffix=":",
213 empty_permitted=False, instance=None):
214
215 opts = self._meta
216
217 if instance is None:
218 self.instance = opts.document()
219 object_data = {}
220 else:
221 self.instance = instance
222 object_data = document_to_dict(instance, opts.properties,
223 opts.exclude)
224
225 if initial is not None:
226 object_data.update(initial)
227
228 super(BaseDocumentForm, self).__init__(data, files, auto_id, prefix,
229 object_data, error_class,
230 label_suffix, empty_permitted)
231
233 """
234 Saves this ``form``'s cleaned_data into document instance
235 ``self.instance``.
236
237 If commit=True, then the changes to ``instance`` will be saved to the
238 database. Returns ``instance``.
239 """
240
241 opts = self._meta
242 cleaned_data = self.cleaned_data.copy()
243 for prop_name in self.instance._doc.keys():
244 if opts.properties and prop_name not in opts.properties:
245 continue
246 if opts.exclude and prop_name in opts.exclude:
247 continue
248 if prop_name in cleaned_data:
249 value = cleaned_data.pop(prop_name)
250 if value is not None:
251 setattr(self.instance, prop_name, value)
252
253 if dynamic:
254 for attr_name in cleaned_data.keys():
255 if opts.exclude and attr_name in opts.exclude:
256 continue
257 value = cleaned_data[attr_name]
258 if value is not None:
259 setattr(self.instance, attr_name, value)
260
261 if commit:
262 self.instance.save()
263
264 return self.instance
265
269
| Home | Trees | Indices | Help |
|---|
| Generated by Epydoc 3.0.1 on Fri May 4 11:48:42 2012 | http://epydoc.sourceforge.net |