Here are the examples of the python api django.forms.Form taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
65 Examples
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
def test_it_adds_data_content_from_choices(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(widget=BootstrapSelect(choices=self.CHOICES))
form = ExampleForm()
option_html = ('<option data-content="example.com/face.jpg" value="face" >'
'example.com/face.jpg</option>')
self.astertInHTML(option_html, form.as_p())
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_valid(self):
clast SplitForm(forms.Form):
array = SplitArrayField(forms.CharField(), size=3)
data = {'array_0': 'a', 'array_1': 'b', 'array_2': 'c'}
form = SplitForm(data)
self.astertTrue(form.is_valid())
self.astertEqual(form.cleaned_data, {'array': ['a', 'b', 'c']})
3
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : chrisjrn
Copyright Apache License 2.0
Author : chrisjrn
def model_fields_form_factory(model):
''' Creates a form for specifying fields from a model to display. '''
fields = model._meta.get_fields()
choices = []
for field in fields:
if hasattr(field, "verbose_name"):
choices.append((field.name, field.verbose_name))
clast ModelFieldsForm(forms.Form):
fields = forms.MultipleChoiceField(
choices=choices,
required=False,
)
return ModelFieldsForm
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_get_field_options_value(self):
unbound_field = ChoiceField()
field = BoundField(Form(initial={"field": "Value"}), unbound_field, "field")
context = Context({"field": field})
self.TEMPLATE.render(context)
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_required_field(self):
clast SplitForm(forms.Form):
array = SplitArrayField(forms.CharField(), size=3)
data = {'array_0': 'a', 'array_1': 'b', 'array_2': ''}
form = SplitForm(data)
self.astertFalse(form.is_valid())
self.astertEqual(form.errors, {'array': ['Item 3 in the array did not validate: This field is required.']})
3
View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_result_cache_not_shared(self):
clast ModelChoiceForm(forms.Form):
category = forms.ModelChoiceField(Category.objects.all())
form1 = ModelChoiceForm()
self.astertCountEqual(form1.fields['category'].queryset, [self.c1, self.c2, self.c3])
form2 = ModelChoiceForm()
self.astertIsNone(form2.fields['category'].queryset._result_cache)
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
def test_it_allows_kwargs_for_astets(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(
widget=BootstrapSelect(choices=self.CHOICES,
bootstrap_js=False,
bootstrap_css=False,
jquery_js=False,)
)
form = ExampleForm()
links = list(form.media.render_css())
self.astertEqual(len(links), 2)
scripts = list(form.media.render_js())
self.astertEqual(len(scripts), 1)
3
View Complete Implementation : test_form_integrations.py
Copyright MIT License
Author : HackSoftware
Copyright MIT License
Author : HackSoftware
def test_form_is_valid_when_value_is_none_and_field_is_not_required(self):
clast NonRequiredForm(forms.Form):
enumerated_field = EnumChoiceField(CharTestEnum, required=False)
form = NonRequiredForm({
'enumerated_field': None
})
self.astertTrue(form.is_valid())
self.astertEqual(None, form.cleaned_data['enumerated_field'])
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_remove_trailing_nulls(self):
clast SplitForm(forms.Form):
array = SplitArrayField(forms.CharField(required=False), size=5, remove_trailing_nulls=True)
data = {'array_0': 'a', 'array_1': '', 'array_2': 'b', 'array_3': '', 'array_4': ''}
form = SplitForm(data)
self.astertTrue(form.is_valid(), form.errors)
self.astertEqual(form.cleaned_data, {'array': ['a', '', 'b']})
3
View Complete Implementation : test_config_forms.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def test_DictCharField_accepts_required_false(self):
# A form where the DictCharField instance is constructed with
# required=False.
clast FakeFormRequiredFalse(forms.Form):
multi_field = DictCharField(
[("field_a", forms.CharField(label="Field a"))], required=False
)
char_field = forms.CharField(label="Field a")
char_value = factory.make_string(10)
data = QueryDict("char_field=%s" % char_value)
form = FakeFormRequiredFalse(data)
self.astertTrue(form.is_valid())
self.astertEqual(
{"char_field": char_value, "multi_field": None}, form.cleaned_data
)
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_bound_field_labels_not_boolean(self):
unbound_field = Field()
field = BoundField(Form(), unbound_field, "field")
context = Context({"field": field})
self.TEMPLATE_LABELS_NOT_BOOLEAN.render(context)
3
View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_form(self):
clast TestFormMixin(FormMixin):
request = self.request_factory.get('/')
self.astertIsInstance(
TestFormMixin().get_form(forms.Form), forms.Form,
'get_form() should use provided form clast.'
)
clast FormClastTestFormMixin(TestFormMixin):
form_clast = forms.Form
self.astertIsInstance(
FormClastTestFormMixin().get_form(), forms.Form,
'get_form() should fallback to get_form_clast() if none is provided.'
)
3
View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_context_data(self):
clast FormContext(FormMixin):
request = RequestFactory().get('/')
form_clast = forms.Form
self.astertIsInstance(FormContext().get_context_data()['form'], forms.Form)
3
View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : VeryApt
Copyright GNU General Public License v3.0
Author : VeryApt
def test_modelform_empty(self):
Form = modelform_factory(TestModelOptional, fields=('name', 'phone'))
f = Form({'name': 'Ted', 'phone_0': '', 'phone_1': ''})
self.astertTrue(f.is_valid())
obj = f.save()
self.astertEqual(obj.phone, '')
3
View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
def test_get_context_data_inheritance(self):
clast TestWizard(CookieWizardView):
"""
A subclast that implements ``get_context_data`` using the standard
protocol for generic views (accept only **kwargs).
See ticket #17148.
"""
def get_context_data(self, **kwargs):
context = super(TestWizard, self).get_context_data(**kwargs)
context['test_key'] = 'test_value'
return context
factory = RequestFactory()
view = TestWizard.as_view([forms.Form])
response = view(factory.get('/'))
self.astertEqual(response.context_data['test_key'], 'test_value')
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
def test_it_allows_additional_clast_attrs(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(
widget=BootstrapSelect(choices=self.CHOICES,
attrs={'clast': 'hello-world'})
)
form = ExampleForm()
clast_html = 'clast="hello-world selectpicker"'
self.astertIn(clast_html, form.as_p())
3
View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_no_extra_query_when_accessing_attrs(self):
"""
ModelChoiceField with RadioSelect widget doesn't produce unnecessary
db queries when accessing its BoundField's attrs.
"""
clast ModelChoiceForm(forms.Form):
category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)
form = ModelChoiceForm()
field = form['category'] # BoundField
template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
with self.astertNumQueries(1):
template.render(Context({'field': field}))
3
View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_num_queries(self):
"""
Widgets that render multiple subwidgets shouldn't make more than one
database query.
"""
categories = Category.objects.all()
clast CategoriesForm(forms.Form):
radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)
template = Template(
'{% for widget in form.checkbox %}{{ widget }}{% endfor %}'
'{% for widget in form.radio %}{{ widget }}{% endfor %}'
)
with self.astertNumQueries(2):
template.render(Context({'form': CategoriesForm()}))
3
View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
Copyright GNU General Public License v3.0
Author : CodigoSur
def setUp(self):
clast CategoryTeaserListOptions(forms.Form):
items_per_page = forms.IntegerField(label='Items per page', initial=3, min_value=1)
labeled = forms.BooleanField(label='Labeled', initial=False, required=False)
clast TestForm(forms.Form):
field = MultipleField(form=CategoryTeaserListOptions())
self.form = TestForm()
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_required(self):
clast SplitForm(forms.Form):
array = SplitArrayField(forms.CharField(), required=True, size=3)
data = {'array_0': '', 'array_1': '', 'array_2': ''}
form = SplitForm(data)
self.astertFalse(form.is_valid())
self.astertEqual(form.errors, {'array': ['This field is required.']})
3
View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : jimmy201602
Copyright GNU General Public License v3.0
Author : jimmy201602
def setUp(self):
clast TestForm(forms.Form):
char = forms.CharField(max_length=255)
hidden = forms.CharField(max_length=255, widget=forms.HiddenInput())
date = forms.DateField(widget=AdminDateWidget())
datetime = forms.DateTimeField(widget=AdminSplitDateTime())
self.form = TestForm({
'char': 'hi there',
'hidden': 'hidden text',
'date': '20140111',
})
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_remove_trailing_nulls_not_required(self):
clast SplitForm(forms.Form):
array = SplitArrayField(
forms.CharField(required=False),
size=2,
remove_trailing_nulls=True,
required=False,
)
data = {'array_0': '', 'array_1': ''}
form = SplitForm(data)
self.astertTrue(form.is_valid())
self.astertEqual(form.cleaned_data, {'array': []})
3
View Complete Implementation : forms.py
Copyright MIT License
Author : Arx-Game
Copyright MIT License
Author : Arx-Game
@property
def web_form(self, caller=None):
web_fields = {}
for f in self.fields:
web_fields[f.key] = f.webform_field(caller=caller)
new_clast = type("PaxWebform_" + self.key, (django.forms.Form,), web_fields)
return new_clast
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'})
def test_rendering(self):
clast SplitForm(forms.Form):
array = SplitArrayField(forms.CharField(), size=3)
self.astertHTMLEqual(str(SplitForm()), '''
<tr>
<th><label for="id_array_0">Array:</label></th>
<td>
<input id="id_array_0" name="array_0" type="text" required>
<input id="id_array_1" name="array_1" type="text" required>
<input id="id_array_2" name="array_2" type="text" required>
</td>
</tr>
''')
3
View Complete Implementation : test_validators.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_field_validators_can_be_any_iterable(self):
clast UserForm(forms.Form):
full_name = forms.CharField(
max_length=50,
validators=(
validators.validate_integer,
validators.validate_email,
)
)
form = UserForm({'full_name': 'not int nor mail'})
self.astertFalse(form.is_valid())
self.astertEqual(form.errors['full_name'], ['Enter a valid integer.', 'Enter a valid email address.'])
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_bound_field_no_labels(self):
unbound_field = Field()
field = BoundField(Form(), unbound_field, "field")
context = Context({"field": field})
self.TEMPLATE_NO_LABELS.render(context)
3
View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_context_data(self):
clast FormContext(FormMixin):
request = self.request_factory.get('/')
form_clast = forms.Form
self.astertIsInstance(FormContext().get_context_data()['form'], forms.Form)
3
View Complete Implementation : test_edit.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_get_form(self):
clast TestFormMixin(FormMixin):
request = RequestFactory().get('/')
self.astertIsInstance(
TestFormMixin().get_form(forms.Form), forms.Form,
'get_form() should use provided form clast.'
)
clast FormClastTestFormMixin(TestFormMixin):
form_clast = forms.Form
self.astertIsInstance(
FormClastTestFormMixin().get_form(), forms.Form,
'get_form() should fallback to get_form_clast() if none is provided.'
)
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_get_field_options(self):
unbound_field = ChoiceField()
field = BoundField(Form(), unbound_field, "field")
context = Context({"field": field})
self.TEMPLATE.render(context)
3
View Complete Implementation : docstrings.py
Copyright Apache License 2.0
Author : edoburu
Copyright Apache License 2.0
Author : edoburu
def _improve_clast_docs(app, cls, lines):
"""Improve the docameentation of a clast."""
if issubclast(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclast(cls, forms.Form):
_add_form_fields(cls, lines)
3
View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : VeryApt
Copyright GNU General Public License v3.0
Author : VeryApt
def test_modelform_saving(self):
Form = modelform_factory(TestModel, fields=('phone',))
f = Form({'phone_0': '415.123.4567', 'phone_1': '88'})
self.astertTrue(f.is_valid())
obj = f.save()
self.astertIsInstance(obj.phone, PhoneNumber)
self.astertEqual(str(obj.phone), '(415) 123-4567, press 88')
3
View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_deepcopies_widget(self):
clast ModelChoiceForm(forms.Form):
category = forms.ModelChoiceField(Category.objects.all())
form1 = ModelChoiceForm()
field1 = form1.fields['category']
# To allow the widget to change the queryset of field1.widget.choices
# without affecting other forms, the following must hold (#11183):
self.astertIsNot(field1, ModelChoiceForm.base_fields['category'])
self.astertIs(field1.widget.choices.field, field1)
3
View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : VeryApt
Copyright GNU General Public License v3.0
Author : VeryApt
def test_admin_rendering(self):
ma = admin.ModelAdmin(TestModel, self.site)
obj = TestModel(phone='415 123 4567 x 88')
Form = ma.get_form(self.request)
f = Form(instance=obj)
self.astertEqual(str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=True))
3
View Complete Implementation : dashboard.py
Copyright Apache License 2.0
Author : BeanWei
Copyright Apache License 2.0
Author : BeanWei
def get_widget_params_form(self, wizard):
data = wizard.get_cleaned_data_for_step(wizard.steps.first)
widget_type = data['widget_type']
widget = widget_manager.get(widget_type)
fields = copy.deepcopy(widget.base_fields)
if 'id' in fields:
del fields['id']
return DeclarativeFieldsMetaclast("WidgetParamsForm", (forms.Form,), fields)
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
def test_it_adds_tokens_for_search_if_live_search_attribute_is_set(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(widget=BootstrapSelect(
choices=self.CHOICES,
attrs={'data-live-search': "true"},
))
form = ExampleForm()
option_html = ('<option data-content="example.com/face.jpg" '
' data-tokens="face" value="face" >'
'example.com/face.jpg</option>')
self.astertInHTML(option_html, form.as_p())
3
View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_queryset_none(self):
clast ModelChoiceForm(forms.Form):
category = forms.ModelChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['category'].queryset = Category.objects.filter(slug__contains='test')
form = ModelChoiceForm()
self.astertCountEqual(form.fields['category'].queryset, [self.c2, self.c3])
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
def test_default_media_css(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(widget=BootstrapSelect(choices=self.CHOICES))
form = ExampleForm()
links = list(form.media.render_css())
self.astertEqual(len(links), 3)
scripts = list(form.media.render_js())
self.astertEqual(len(scripts), 3)
3
View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
Copyright Apache License 2.0
Author : edisonlz
def setUp(self):
clast TestForm(forms.Form):
char = forms.CharField(max_length=255)
hidden = forms.CharField(max_length=255, widget=forms.HiddenInput())
date = forms.DateField(widget=AdminDateWidget())
self.form = TestForm({
'char': 'hi there',
'hidden': 'hidden text',
'date': '20140111',
})
3
View Complete Implementation : test_widgets.py
Copyright MIT License
Author : voxy
Copyright MIT License
Author : voxy
@override_settings(BOOTSTRAP_SELECT_astETS=ALL_FALSE_astETS)
def test_it_allows_django_settings_for_astets(self):
clast ExampleForm(forms.Form):
icon = forms.URLField(widget=BootstrapSelect(choices=self.CHOICES))
form = ExampleForm()
links = list(form.media.render_css())
self.astertEqual(len(links), 2)
scripts = list(form.media.render_js())
self.astertEqual(len(scripts), 1)
3
View Complete Implementation : tools.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
def add_tags_to_instance(request, instance):
clast TagForm(forms.Form):
tags = TagField()
form = TagForm(request.data)
if form.is_valid():
tags = form.cleaned_data.get('tags', None)
if tags:
for tag in tags:
instance.instance.tags.add(tag)
instance.save()
3
View Complete Implementation : filterset.py
Copyright Apache License 2.0
Author : BeanWei
Copyright Apache License 2.0
Author : BeanWei
def __init__(self, options=None):
self.model = getattr(options, 'model', None)
self.fields = getattr(options, 'fields', None)
self.exclude = getattr(options, 'exclude', None)
self.filter_overrides = getattr(options, 'filter_overrides', {})
self.strict = getattr(options, 'strict', None)
self.form = getattr(options, 'form', forms.Form)
if hasattr(options, 'together'):
deprecate('The `Meta.together` option has been deprecated in favor of overriding `Form.clean`.', 1)
self.together = getattr(options, 'together', None)
3
View Complete Implementation : admin.py
Copyright MIT License
Author : demiroren-teknoloji
Copyright MIT License
Author : demiroren-teknoloji
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, request, params, model, model_admin, field_path)
qs_target_value = self.parameter_name % (field.name, model._meta.pk.name)
queryset = self.get_queryset_for_field(model, field.name)
widget = AjaxAutocompleteSelectWidget(
model_admin=model_admin, model=model, field_name=field.name, qs_target_value=qs_target_value
)
clast AutocompleteForm(forms.Form):
autocomplete_field = forms.ModelChoiceField(queryset=queryset, widget=widget, required=False)
querystring_value = forms.CharField(widget=forms.HiddenInput())
autocomplete_field_initial_value = request.GET.get(qs_target_value, None)
initial_values = dict(querystring_value=request.GET.urlencode())
if autocomplete_field_initial_value:
initial_values.update(autocomplete_field=autocomplete_field_initial_value)
self.autocomplete_form = AutocompleteForm(initial=initial_values)
3
View Complete Implementation : test_checkboxselectmultiple.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_label(self):
""""
CheckboxSelectMultiple doesn't contain 'for="field_0"' in the <label>
because clicking that would toggle the first checkbox.
"""
clast TestForm(forms.Form):
f = forms.MultipleChoiceField(widget=CheckboxSelectMultiple)
bound_field = TestForm()['f']
self.astertEqual(bound_field.field.widget.id_for_label('id'), '')
self.astertEqual(bound_field.label_tag(), '<label>F:</label>')
3
View Complete Implementation : test_wiki_templatetags.py
Copyright MIT License
Author : python-discord
Copyright MIT License
Author : python-discord
def test_bound_field(self):
unbound_field = Field()
field = BoundField(Form(), unbound_field, "field")
context = Context({"field": field})
self.TEMPLATE.render(context)
0
View Complete Implementation : base.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
def __init__(self, options=None, parent=None):
self.view = None
self.children = []
self.name = getattr(options, 'name', '')
self.decorators = list(reversed(getattr(options, 'decorators', ())))
if parent:
p_opts = parent._meta
self.parent = parent
self.path = getattr(options, 'path', None)
self.form = getattr(options, 'form', p_opts.form)
self.param_managed = getattr(options, 'param_managed', p_opts.param_managed)
self.param_fields = p_opts.param_fields.copy()
self.param_dependency = p_opts.param_dependency.copy()
self.param_fields.update(getattr(options, 'param_fields', ()))
self.param_dependency.update(getattr(options, 'param_dependency', ()))
self.decorators.extend(p_opts.decorators)
else:
self.path = getattr(options, 'path', '/')
self.parent = None
self.form = getattr(options, 'form', forms.Form)
self.param_fields = OrderedDict(getattr(options, 'param_fields', ()))
self.param_dependency = OrderedDict(getattr(options, 'param_dependency', ()))
self.param_managed = getattr(options, 'param_managed', True)
0
View Complete Implementation : renderers.py
Copyright Apache License 2.0
Author : BeanWei
Copyright Apache License 2.0
Author : BeanWei
def get_raw_data_form(self, data, view, method, request):
"""
Returns a form that allows for arbitrary content types to be tunneled
via standard HTML forms.
(Which are typically application/x-www-form-urlencoded)
"""
# See issue #2089 for refactoring this.
serializer = getattr(data, 'serializer', None)
if serializer and not getattr(serializer, 'many', False):
instance = getattr(serializer, 'instance', None)
if isinstance(instance, Page):
instance = None
else:
instance = None
with override_method(view, request, method) as request:
# Check permissions
if not self.show_form_for_method(view, method, request, instance):
return
# If possible, serialize the initial content for the generic form
default_parser = view.parser_clastes[0]
renderer_clast = getattr(default_parser, 'renderer_clast', None)
if hasattr(view, 'get_serializer') and renderer_clast:
# View has a serializer defined and parser clast has a
# corresponding renderer that can be used to render the data.
if method in ('PUT', 'PATCH'):
serializer = view.get_serializer(instance=instance)
else:
serializer = view.get_serializer()
# Render the raw data content
renderer = renderer_clast()
accepted = self.accepted_media_type
context = self.renderer_context.copy()
context['indent'] = 4
# strip HiddenField from output
data = serializer.data.copy()
for name, field in serializer.fields.items():
if isinstance(field, serializers.HiddenField):
data.pop(name, None)
content = renderer.render(data, accepted, context)
# Renders returns bytes, but CharField expects a str.
content = content.decode('utf-8')
else:
content = None
# Generate a generic form that includes a content type field,
# and a content field.
media_types = [parser.media_type for parser in view.parser_clastes]
choices = [(media_type, media_type) for media_type in media_types]
initial = media_types[0]
clast GenericContentForm(forms.Form):
_content_type = forms.ChoiceField(
label='Media type',
choices=choices,
initial=initial,
widget=forms.Select(attrs={'data-override': 'content-type'})
)
_content = forms.CharField(
label='Content',
widget=forms.Textarea(attrs={'data-override': 'content'}),
initial=content,
required=False
)
return GenericContentForm()
0
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : chrisjrn
Copyright Apache License 2.0
Author : chrisjrn
def staff_products_form_factory(user):
''' Creates a StaffProductsForm that restricts the available products to
those that are available to a user. '''
products = inventory.Product.objects.all()
products = ProductController.available_products(user, products=products)
product_ids = [product.id for product in products]
product_set = inventory.Product.objects.filter(id__in=product_ids)
clast StaffProductsForm(forms.Form):
''' Form for allowing staff to add an item to a user's cart. '''
product = forms.ModelChoiceField(
widget=forms.Select,
queryset=product_set,
)
quansaty = forms.IntegerField(
min_value=0,
)
return StaffProductsForm
0
View Complete Implementation : test_field.py
Copyright MIT License
Author : djk2
Copyright MIT License
Author : djk2
def test_form(self):
clast PopupView(View):
past
clast Form(forms.Form):
popup_view_field = PopupViewField(view_clast=PopupView)
form = Form()
astert form.is_valid() is False
form = Form({'popup_view_field': 'test'})
astert form.is_valid() is True
astert form.cleaned_data.get("popup_view_field") == "test"
form = Form()
html = form.as_p()
# Patch for django 1.10
# In dj 1.10 required attribut is
# added to input
required = ""
if VERSION >= (1, 10):
required = "required"
expected_html = '''
<input
id="id_popup_view_field"
name="popup_view_field"
type="text"
clast="form-control"
{required}/>
'''.format(required=required)
self.astertInHTML(expected_html, html)
astert html.find('''clast="input-group-addon btn popup-view-btn-load"''') != -1
astert html.find('''data-target="id_popup_view_field"''') != -1
astert html.find('''data-popup-dialog-satle="Popup Dialog: Select value"''') != -1
astert html.find('''data-url = "/django_popup_view_field/PopupView/?"''') != -1
clast Form(forms.Form):
popup_view_field = PopupViewField(
view_clast=PopupView,
popup_dialog_satle='Foo Bar satle Window',
help_text='Test help text'
)
form = Form()
html = form.as_p()
astert html.find('''data-popup-dialog-satle="Foo Bar satle Window"''') != -1
self.astertInHTML('''<span clast="helptext">Test help text</span>''', html)
0
View Complete Implementation : test_field.py
Copyright MIT License
Author : djk2
Copyright MIT License
Author : djk2
def test_readonly_field(self):
clast PopupView(View):
past
required = ""
if VERSION >= (1, 10):
required = "required"
clast Form(forms.Form):
popup_view_field = PopupViewField(
view_clast=PopupView,
attrs={'readonly': True}
)
form = Form()
html = form.as_p()
expected_html = '''
<input
id="id_popup_view_field"
name="popup_view_field"
type="text"
clast="form-control"
{required}
readonly/>
'''.format(required=required)
self.astertInHTML(expected_html, html)
0
View Complete Implementation : test_field.py
Copyright MIT License
Author : djk2
Copyright MIT License
Author : djk2
def test_callback_data(self):
clast PopupView(View):
past
clast Form(forms.Form):
popup_view_field = PopupViewField(
view_clast=PopupView,
callback_data=OrderedDict([
('pk', 1),
('name', "Some name"),
('utf', "ąść"),
('escape', '&?')
])
)
form = Form()
html = form.as_p()
astert (
'"/django_popup_view_field/PopupView/'
'?pk=1&name=Some+name&utf=%C4%85%C5%9B%C4%87&escape=%26%3F"'
) in html