def test_error_and_help_inline(): form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() form.helper.error_text_inline = False form.helper.help_text_inline = True form.helper.layout = Layout("email") form.is_valid() html = render_crispy_form(form) # Check that help goes before error, otherwise CSS won't work help_position = html.find('<span id="hint_id_email" class="help-inline">') error_position = html.find('<p id="error_1_id_email" class="help-block">') assert help_position < error_position # Viceversa form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() form.helper.error_text_inline = True form.helper.help_text_inline = False form.helper.layout = Layout("email") form.is_valid() html = render_crispy_form(form) # Check that error goes before help, otherwise CSS won't work error_position = html.find('<span id="error_1_id_email" class="help-inline">') help_position = html.find('<p id="hint_id_email" class="help-block">') assert error_position < help_position
def multi_molecule(request, string): if request.REQUEST.get("random"): amount = int(request.REQUEST.get("random")) string = ','.join(name_expansion(string, rand=amount)) job_form = JobForm.get_form(request, "{{ name }}") mol_form = MoleculeForm(request.REQUEST) job_is_valid = job_form.is_valid(request.method) mol_is_valid = mol_form.is_valid() if job_is_valid and mol_is_valid: return job_form.get_results(request, string, mol_form) elif request.is_ajax(): job_form_html = render_crispy_form( job_form, context=RequestContext(request)) mol_form_html = render_crispy_form( mol_form, context=RequestContext(request)) a = { "success": False, "job_form_html": job_form_html, "mol_form_html": mol_form_html, } return HttpResponse(json.dumps(a), content_type="application/json") c = { "pagename": string, "job_form": job_form, "mol_form": MoleculeForm(), "gjf": "checked", "autoflip": request.REQUEST.get("autoflip"), } return render(request, "chem/multi_molecule.html", c)
def detallePedidoAlaboratorio_add(request): success = True id_laboratorio = request.session['pedidoAlaboratorio']['laboratorio']['id'] if request.method == 'POST': form = forms.DetallePedidoAlaboratorioFormFactory(id_laboratorio)(request.POST) if form.is_valid(): det = form.save(commit=False) detalles = request.session["detallesPedidoAlaboratorio"] if not utils.existe_medicamento_en_detalle_suelto(detalles, det.medicamento.id): detallePedidoAlaboratorio_json = utils.crear_detalle_json(det, len(detalles) + 1) # detalle suelto no se corresponde con ningun detalle de pedido de farmacia detallePedidoAlaboratorio_json['detallePedidoFarmacia'] = -1 detalles.append(detallePedidoAlaboratorio_json) request.session["detallesPedidoAlaboratorio"] = detalles # Nuevo form para seguir dando de alta form = forms.DetallePedidoAlaboratorioFormFactory(id_laboratorio)() form_html = render_crispy_form(form, context=update_csrf(request)) return {'success': success, 'form_html': form_html, 'detalles': detalles} else: return {'success': False} else: success = False else: form = forms.DetallePedidoAlaboratorioFormFactory(id_laboratorio)() form_html = render_crispy_form(form, context=update_csrf(request)) return {'success': success, 'form_html': form_html}
def molecule_detail(request, molecule): job_form = JobForm.get_form(request, molecule) mol_form = MoleculeForm(request.REQUEST) job_is_valid = job_form.is_valid(request.method) mol_is_valid = mol_form.is_valid() if job_is_valid and mol_is_valid: return job_form.get_results(request, molecule, mol_form) elif request.is_ajax(): job_form_html = render_crispy_form( job_form, context=RequestContext(request)) mol_form_html = render_crispy_form( mol_form, context=RequestContext(request)) a = { "success": False, "job_form_html": job_form_html, "mol_form_html": mol_form_html, } return HttpResponse(json.dumps(a), content_type="application/json") a = get_molecule_info_status(molecule) a["job_form"] = job_form a["mol_form"] = MoleculeForm() return render(request, "chem/molecule_detail.html", a)
def test_bootstrap_form_show_errors(): form = TestForm( { "email": "invalidemail", "first_name": "first_name_too_long", "last_name": "last_name_too_long", "password1": "yes", "password2": "yes", } ) form.helper = FormHelper() form.helper.layout = Layout( AppendedText("email", "whatever"), PrependedText("first_name", "blabla"), PrependedAppendedText("last_name", "foo", "bar"), AppendedText("password1", "whatever"), PrependedText("password2", "blabla"), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) assert html.count("error") == 6 form.helper.form_show_errors = False html = render_crispy_form(form) assert html.count("error") == 0
def postPoint(request, Form): """Submit a user point submission to the database. Normalize geometry and activate push notifications.""" form = Form(request.POST) form.data = form.data.copy() # Convert coords to valid geometry try: form.data['geom'] = normalizeGeometry(form.data['geom']) except(ValueError): # TODO provide error message to user here JsonResponse({'success': False}) # messages.error(request, '<strong>' + _('Error') + '</strong><br>' + _('No point was selected for this type of report.')) # Validate and submit to db if form.is_valid(): point = form.save() # Errors with push notifications should not affect reporting if not settings.DEBUG: try: pushNotification.pushNotification(point) except: pass return JsonResponse({ 'success': True, 'point': GeoJSONSerializer().serialize([point,]), 'point_type': point.p_type, 'form_html': render_crispy_form(Form()) }) else: logger.debug("Form not valid") # Else: error occurred form.data['geom'] = form.data['geom'].json form_html = render_crispy_form(form) return JsonResponse({'success': False, 'form_html': form_html})
def test_error_text_inline(settings): form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() layout = Layout( AppendedText("first_name", "wat"), PrependedText("email", "@"), PrependedAppendedText("last_name", "@", "wat") ) form.helper.layout = layout form.is_valid() html = render_crispy_form(form) help_class = "help-inline" if settings.CRISPY_TEMPLATE_PACK == "bootstrap3": help_class = "help-block" matches = re.findall('<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE) assert len(matches) == 3 form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() form.helper.layout = layout form.helper.error_text_inline = False html = render_crispy_form(form) matches = re.findall('<p id="error_\d_\w*" class="help-block"', html, re.MULTILINE) assert len(matches) == 3
def others_edit_view(request, model_name, **kwargs): perm = getattr(get_user_profile(request.user), model_name + '_permission') or request.user.is_superuser form_class = crispy_form_factory(model=model_name_dict[model_name], widgets=widgets_dict[model_name], disabled=[], exclude=[], ) if request.method == 'GET': edit_form = form_class(instance=get_object_or_404(model_name_dict[model_name], id=kwargs['id'])) request_context = csrf(request) form_html = render_crispy_form(edit_form, context=request_context) return HttpResponse(json.dumps({'form_html': form_html})) if request.method == 'POST': if perm: edit_form = form_class(request.POST, instance=get_object_or_404(model_name_dict[model_name], id=kwargs['id'])) if edit_form.is_valid(): edit_form.save() return HttpResponse(json.dumps({'success': True})) else: request_context = csrf(request) form_html = render_crispy_form(edit_form, context=request_context) return HttpResponse(json.dumps({'success': False, 'permission': True, 'form_html': form_html})) else: return HttpResponse(json.dumps({'success': False, 'permission': False}))
def test_accordion_active_false_not_rendered(self, settings): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( Accordion( AccordionGroup("one", "first_name"), # there is no ``active`` kwarg here. ) ) # The first time, there should be one of them there. html = render_crispy_form(test_form) if settings.CRISPY_TEMPLATE_PACK == "bootstrap": accordion_class = "accordion-body" else: accordion_class = "panel-collapse" assert html.count('<div id="one" class="%s collapse in"' % accordion_class) == 1 test_form.helper.layout = Layout( Accordion(AccordionGroup("one", "first_name", active=False)) # now ``active`` manually set as False ) # This time, it shouldn't be there at all. html = render_crispy_form(test_form) assert html.count('<div id="one" class="%s collapse in"' % accordion_class) == 0
def edit_view(request, model_name, **kwargs): objs_and_perm = get_objs_and_perm(request.user, **kwargs) higher_model_name = higher_model_name_dict[model_name] if higher_model_name is None: disabled = [] else: disabled = [higher_model_name] form_class = crispy_form_factory(model=model_name_dict[model_name], widgets=widgets_dict[model_name], disabled=disabled, exclude=[], ) if request.method == 'GET': edit_form = form_class(instance=objs_and_perm[model_name]) request_context = csrf(request) form_html = render_crispy_form(edit_form, context=request_context) return HttpResponse(json.dumps({'form_html': form_html})) if request.method == 'POST': if objs_and_perm['perm']: POST = request.POST.copy() if higher_model_name is not None: POST[higher_model_name] = objs_and_perm.get(higher_model_name).id edit_form = form_class(POST, instance=objs_and_perm[model_name]) if edit_form.is_valid(): edit_form.save() return HttpResponse(json.dumps({'success': True})) else: request_context = csrf(request) form_html = render_crispy_form(edit_form, context=request_context) return HttpResponse(json.dumps({'success': False, 'permission': True, 'form_html': form_html})) else: return HttpResponse(json.dumps({'success': False, 'permission': False}))
def others_add_view(request, model_name): # this view is for non-leveled model perm = getattr(get_user_profile(request.user), model_name + '_permission') or request.user.is_superuser form_class = crispy_form_factory(model=model_name_dict[model_name], widgets=widgets_dict[model_name], disabled=[], exclude=[], ) if request.method == 'GET': add_form = form_class() request_context = csrf(request) form_html = render_crispy_form(add_form, context=request_context) return HttpResponse(json.dumps({'form_html': form_html})) if request.method == 'POST': if perm: add_form = form_class(request.POST) if add_form.is_valid(): add_form.save() return HttpResponse(json.dumps({'success': True})) else: request_context = csrf(request) form_html = render_crispy_form(add_form, context=request_context) return HttpResponse(json.dumps({'success': False, 'permission': True, 'form_html': form_html})) else: return HttpResponse(json.dumps({'success': False, 'permission': False}))
def test_bootstrap_form_show_errors(): form = TestForm({ 'email': 'invalidemail', 'first_name': 'first_name_too_long', 'last_name': 'last_name_too_long', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( AppendedText('email', 'whatever'), PrependedText('first_name', 'blabla'), PrependedAppendedText('last_name', 'foo', 'bar'), AppendedText('password1', 'whatever'), PrependedText('password2', 'blabla'), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) assert html.count('error') == 3 form.helper.form_show_errors = False html = render_crispy_form(form) assert html.count('error') == 0
def test_error_text_inline(settings): form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() layout = Layout( AppendedText('first_name', 'wat'), PrependedText('email', '@'), PrependedAppendedText('last_name', '@', 'wat'), ) form.helper.layout = layout form.is_valid() html = render_crispy_form(form) help_class = 'help-inline' if settings.CRISPY_TEMPLATE_PACK in ['bootstrap3', 'bootstrap4']: help_class = 'help-block' matches = re.findall( '<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE ) assert len(matches) == 3 form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.layout = layout form.helper.error_text_inline = False html = render_crispy_form(form) matches = re.findall('<p id="error_\d_\w*" class="help-block"', html, re.MULTILINE) assert len(matches) == 3
def post_ajax(self, request, obj=None, *args, **kwargs): if self.ajax_form is None: raise ImproperlyConfigured( "%(cls)s is missing the form. " "Define %(cls)s.form." % {"cls": self.__class__.__name__}) in_data = json.loads(request.body) test_msg = self.json_in_data_test(in_data, request) if test_msg: return HttpResponseBadRequest(json.dumps({'msg': test_msg}), mimetype="application/json") model = self.ajax_form._meta.model._meta.model_name scope_prefix = '_'.join([model, 'data']) if self.kwargs.has_key('pk'): obj = get_object_or_404(self.ajax_form._meta.model, pk=self.kwargs['pk']) bound_form = self.ajax_form(data=in_data, instance=obj, scope_prefix=scope_prefix, user=request.user) bound_form.full_clean() if bound_form.is_valid(): instance = bound_form.save(commit=False) instance = self.update_form_fields(instance, request, in_data, bound_form) instance.save() form_html = render_crispy_form(bound_form) if obj: msg = '%s successfully updated!' % model.capitalize() else: msg = '%s successfully created!' % model.capitalize() return HttpResponse(json.dumps({'msg': msg, 'form_html': form_html,}), mimetype="application/json") else: form_html = render_crispy_form(bound_form) msg = 'Invalid form: please correct the errors below:' return HttpResponseBadRequest(json.dumps({'msg': msg, 'form_html': form_html}), mimetype="application/json")
def test_form_show_errors(): form = TestForm({ 'email': 'invalidemail', 'first_name': 'first_name_too_long', 'last_name': 'last_name_too_long', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( Field('email'), Field('first_name'), Field('last_name'), Field('password1'), Field('password2'), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) assert html.count('error') == 9 form.helper.form_show_errors = False html = render_crispy_form(form) assert html.count('error') == 0
def test_multifield_errors(self): if settings.CRISPY_TEMPLATE_PACK != 'uni_form': warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm({ 'email': 'invalidemail', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( MultiField('legend', 'email') ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count('error'), 3) # Reset layout for avoiding side effects form.helper.layout = Layout( MultiField('legend', 'email') ) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count('error'), 0)
def test_error_text_inline(self): form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() layout = Layout( AppendedText('first_name', 'wat'), PrependedText('email', '@'), PrependedAppendedText('last_name', '@', 'wat'), ) form.helper.layout = layout form.is_valid() html = render_crispy_form(form) help_class = 'help-inline' if self.current_template_pack == 'bootstrap3': help_class = 'help-block' matches = re.findall( '<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE ) self.assertEqual(len(matches), 3) form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.layout = layout form.helper.error_text_inline = False html = render_crispy_form(form) matches = re.findall('<p id="error_\d_\w*" class="help-block"', html, re.MULTILINE) self.assertEqual(len(matches), 3)
def test_render_hidden_fields(self): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( 'email' ) test_form.helper.render_hidden_fields = True html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 1) # Now hide a couple of fields for field in ('password1', 'password2'): test_form.fields[field].widget = forms.HiddenInput() html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 3) self.assertEqual(html.count('hidden'), 2) if django.VERSION < (1, 5): self.assertEqual(html.count('type="hidden" name="password1"'), 1) self.assertEqual(html.count('type="hidden" name="password2"'), 1) else: self.assertEqual(html.count('name="password1" type="hidden"'), 1) self.assertEqual(html.count('name="password2" type="hidden"'), 1)
def test_tab_helper_reuse(self): # this is a proper form, according to the docs. # note that the helper is a class property here, # shared between all instances class TestForm(forms.Form): val1 = forms.CharField(required=False) val2 = forms.CharField(required=True) helper = FormHelper() helper.layout = Layout( TabHolder( Tab('one', 'val1',), Tab('two', 'val2',) ) ) # first render of form => everything is fine test_form = TestForm() html = render_crispy_form(test_form) # second render of form => first tab should be active, # but not duplicate class test_form = TestForm() html = render_crispy_form(test_form) self.assertEqual(html.count('class="tab-pane active active"'), 0) # render a new form, now with errors test_form = TestForm(data={'val1': 'foo'}) html = render_crispy_form(test_form) # tab 1 should not be active self.assertEqual(html.count('<div id="one" \n class="tab-pane active'), 0) # tab 2 should be active self.assertEqual(html.count('<div id="two" \n class="tab-pane active'), 1)
def test_error_and_help_inline(self): form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = False form.helper.help_text_inline = True form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that help goes before error, otherwise CSS won't work if settings.CRISPY_TEMPLATE_PACK == 'bootstrap': help_position = html.find('<span id="hint_id_email" class="help-inline">') error_position = html.find('<p id="error_1_id_email" class="help-block">') self.assertTrue(help_position < error_position) # Viceversa form = TestForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = True form.helper.help_text_inline = False form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that error goes before help, otherwise CSS won't work if settings.CRISPY_TEMPLATE_PACK == 'bootstrap': error_position = html.find('<span id="error_1_id_email" class="help-inline">') help_position = html.find('<p id="hint_id_email" class="help-block">') self.assertTrue(error_position < help_position)
def test_form_show_errors(self): form = TestForm( { "email": "invalidemail", "first_name": "first_name_too_long", "last_name": "last_name_too_long", "password1": "yes", "password2": "yes", } ) form.helper = FormHelper() form.helper.layout = Layout( AppendedText("email", "whatever"), PrependedText("first_name", "blabla"), AppendedPrependedText("last_name", "foo", "bar"), MultiField("legend", "password1", "password2"), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count("error"), 6) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count("error"), 0)
def test_custom_django_widget(self, settings): class CustomRadioSelect(forms.RadioSelect): pass class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple): pass # Make sure an inherited RadioSelect gets rendered as it form = CheckboxesSampleForm() form.fields['inline_radios'].widget = CustomRadioSelect() form.helper = FormHelper() form.helper.layout = Layout('inline_radios') html = render_crispy_form(form) if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4': assert 'class="form-check"' in html else: assert 'class="radio"' in html # Make sure an inherited CheckboxSelectMultiple gets rendered as it form.fields['checkboxes'].widget = CustomCheckboxSelectMultiple() form.helper.layout = Layout('checkboxes') html = render_crispy_form(form) if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4': assert 'class="form-check"' in html else: assert 'class="checkbox"' in html
def test_form_show_errors(self): if settings.CRISPY_TEMPLATE_PACK != 'uni_form': warnings.warn('skipping uniform tests with CRISPY_TEMPLATE_PACK=%s' % settings.CRISPY_TEMPLATE_PACK) return form = TestForm({ 'email': 'invalidemail', 'first_name': 'first_name_too_long', 'last_name': 'last_name_too_long', 'password1': 'yes', 'password2': 'yes', }) form.helper = FormHelper() form.helper.layout = Layout( Field('email'), Field('first_name'), Field('last_name'), Field('password1'), Field('password2'), ) form.is_valid() form.helper.form_show_errors = True html = render_crispy_form(form) self.assertEqual(html.count('error'), 9) form.helper.form_show_errors = False html = render_crispy_form(form) self.assertEqual(html.count('error'), 0)
def test_error_text_inline(self): form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() layout = Layout( AppendedText("first_name", "wat"), PrependedText("email", "@"), PrependedAppendedText("last_name", "@", "wat"), ) form.helper.layout = layout form.is_valid() html = render_crispy_form(form) help_class = "help-inline" if self.current_template_pack == "bootstrap3": help_class = "help-block" matches = re.findall('<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE) self.assertEqual(len(matches), 3) form = TestForm({"email": "invalidemail"}) form.helper = FormHelper() form.helper.layout = layout form.helper.error_text_inline = False html = render_crispy_form(form) matches = re.findall('<p id="error_\d_\w*" class="help-block"', html, re.MULTILINE) self.assertEqual(len(matches), 3)
def test_error_and_help_inline(): form = SampleForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = False form.helper.help_text_inline = True form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that help goes before error, otherwise CSS won't work help_position = html.find('<span id="hint_id_email" class="help-inline">') error_position = html.find('<p id="error_1_id_email" class="invalid-feedback">') assert help_position < error_position # Viceversa form = SampleForm({'email': 'invalidemail'}) form.helper = FormHelper() form.helper.error_text_inline = True form.helper.help_text_inline = False form.helper.layout = Layout('email') form.is_valid() html = render_crispy_form(form) # Check that error goes before help, otherwise CSS won't work error_position = html.find('<span id="error_1_id_email" class="help-inline">') help_position = html.find('<small id="hint_id_email" class="form-text text-muted">') assert error_position < help_position
def test_pubtype(self): c = Client() c.login(username='******', password='******') render_crispy_form(forms.PubtypeForm()) affirm(create_suggestion(data={ 'code':'RPT', 'name':'Report' }), client=c)
def addRiver(request): if request.method == 'POST': form = PlacemarkForm(request.POST or None) if form.is_valid(): user = AuthUser.objects.get(username=request.user.username) """Build Placemark Record""" pm_obj = Placemarks(name = form.cleaned_data['name'], class_field = form.cleaned_data['class_field'], section = form.cleaned_data['section'], description = form.cleaned_data['description'], state = form.cleaned_data['state'], lon = form.cleaned_data['lat'], #Fix this shit lat = form.cleaned_data['lon'], #Fix this shit flow_min = form.cleaned_data['flow_min'], flow_max = form.cleaned_data['flow_max'], stage_min = form.cleaned_data['stage_min'], stage_max = form.cleaned_data['stage_max'],) """If Gauge Field is not empty""" if form.cleaned_data['usgs_gauge']: """Get Gauge object if it already exists, else create it""" try: gauge_obj, created = Gauges.objects.get_or_create(usgs_gauge = form.cleaned_data['usgs_gauge']) except IntegrityError as e: form.errors['__all__'] = form.error_class(['Error getting or creating USGS gauge.']) else: pm_obj.usgs_gauge = gauge_obj """Save new placemark in DB""" try: pm_obj.save() except Exception as e: form.errors['__all__'] = form.error_class(['Error saving new river section']) return {'success': False, 'form_html': render_crispy_form(form, context=RequestContext(request))} """Save new placemark as a user favorite""" try: user.placemarks.add(pm_obj) except Exception as e: form.errors['__all__'] = form.error_class(['Error adding new section to My Rivers.']) form.helper.layout.insert(0, Alert(content="Successfully added river section.", css_class="alert-success")) form.helper[1:11].wrap(Div, css_class='hidden') send_mail('Test Subject','Test Message','Rivers Near Me',['*****@*****.**']) return {'success': True, 'form_html': render_crispy_form(form, context=RequestContext(request))} else: """form is not valid""" form_html = render_crispy_form(form, context=RequestContext(request)) return {'success': False, 'form_html': form_html} elif request.method == 'GET': form = forms.PlacemarkForm() return render(request, 'rivers/crispy.html',{'form': form})
def test_publicationauthor_form_with_publication(self): f = forms.PublicationAuthorForm(publication = models.Publication.objects.create( name='Test publication', pubtype=models.Pubtype.objects.create( code="REP", name="Report") ) ) assert f.helper render_crispy_form(f)
def test_multiplecheckboxes(self): test_form = CheckboxesTestForm() html = render_crispy_form(test_form) self.assertEqual(html.count('checked="checked"'), 5) test_form.helper = FormHelper(test_form) test_form.helper[1].wrap(InlineCheckboxes, inline=True) html = render_crispy_form(test_form) self.assertEqual(html.count('checkbox inline"'), 3) self.assertEqual(html.count('inline"'), 3)
def test_html5_required(): form = TestForm() form.helper = FormHelper() form.helper.html5_required = True html = render_crispy_form(form) # 6 out of 7 fields are required and an extra one for the SplitDateTimeWidget makes 7. assert html.count('required="required"') == 7 form = TestForm() form.helper = FormHelper() form.helper.html5_required = False html = render_crispy_form(form)
def crispy(context, form, **options): helper = FormHelper() helper.form_tag = False for option, value in options.items(): setattr(helper, option, value) return render_crispy_form(form, helper=helper, context=context)
def test_bootstrap3_does_not_add_form_control_class_to_multivaluefield(): form = SampleFormWithMultiValueField() form.helper = FormHelper() form.helper.template_pack = "bootstrap3" html = render_crispy_form(form) assert "form-control" not in html
def crispy(context, form): return render_crispy_form(form, context=context)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = render_crispy_form(self.form_class) return context
def get(self, request, *args, **kwargs): form = self.form_class() form_html = render_crispy_form(form) context = {'form_html': form_html} return context
def test_table_inline_formset(self): SampleFormSet = formset_factory(SampleForm, extra=2) formset = SampleFormSet() formset.helper = FormHelper() formset.helper.form_tag = False formset.helper.add_input(Submit("submit", "submit")) formset.helper.template = "tailwind/table_inline_formset.html" html = render_crispy_form(formset) expected_html = """ <div> <input type="hidden" name="form-TOTAL_FORMS" value="2" id="id_form-TOTAL_FORMS" /> <input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /> <input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS" /> <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS" /> </div> <table class="table-auto"> <thead> <tr> <th for="id_form-0-is_company" class="px-4 py-2"> company </th> <th for="id_form-0-email" class="px-4 py-2">email<span class="asteriskField">*</span></th> <th for="id_form-0-password1" class="px-4 py-2">password<span class="asteriskField">*</span></th> <th for="id_form-0-password2" class="px-4 py-2">re-enter password<span class="asteriskField">*</span></th> <th for="id_form-0-first_name" class="px-4 py-2">first name<span class="asteriskField">*</span></th> <th for="id_form-0-last_name" class="px-4 py-2">last name<span class="asteriskField">*</span></th> <th for="id_form-0-datetime_field" class="px-4 py-2">date time<span class="asteriskField">*</span></th> <th for="id_form-0-tos_accepted" class="px-4 py-2">terms of service<span class="asteriskField">*</span></th> </tr> </thead> <tbody> <tr> <td id="div_id_form-0-is_company" class="border px-4 py-2"><input type="checkbox" name="form-0-is_company" class=" checkboxinput" id="id_form-0-is_company" /></td> <td id="div_id_form-0-email" class="border px-4 py-2"> <input type="text" name="form-0-email" maxlength="30" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-0-email" /> <small id="hint_id_form-0-email" class="text-gray-600">Insert your email</small> </td> <td id="div_id_form-0-password1" class="border px-4 py-2"> <input type="password" name="form-0-password1" maxlength="30" class="passwordinput w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-0-password1" /> </td> <td id="div_id_form-0-password2" class="border px-4 py-2"> <input type="password" name="form-0-password2" maxlength="30" class="passwordinput w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-0-password2" /> </td> <td id="div_id_form-0-first_name" class="border px-4 py-2"> <input type="text" name="form-0-first_name" maxlength="5" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-0-first_name" /> </td> <td id="div_id_form-0-last_name" class="border px-4 py-2"> <input type="text" name="form-0-last_name" maxlength="5" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-0-last_name" /> </td> <td id="div_id_form-0-datetime_field" class="border px-4 py-2"> <input type="text" name="form-0-datetime_field_0" class="dateinput border border-gray-300 text-gray-700 focus:outline-none px-4 mr-2 bg-white focus:outline leading-normal rounded-lg py-2 appearance-none" id="id_form-0-datetime_field_0" /> <input type="text" name="form-0-datetime_field_1" class="timeinput border border-gray-300 text-gray-700 focus:outline-none px-4 mr-2 bg-white focus:outline leading-normal rounded-lg py-2 appearance-none" id="id_form-0-datetime_field_1" /> </td> <td id="div_id_form-0-tos_accepted" class="border px-4 py-2"> <div class="border px-4 py-2"> <div class="relative"> <select class="bg-white focus:outline-none border border-gray-300 rounded-lg py-2 px-4 block w-full appearance-none leading-normal text-gray-700" name="form-0-tos_accepted"> <option value="accepted">Accepted</option> <option value="not_accepted">Not accepted</option> </select> <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> </td> </tr> <tr> <td id="div_id_form-1-is_company" class="border px-4 py-2"><input type="checkbox" name="form-1-is_company" class=" checkboxinput" id="id_form-1-is_company" /></td> <td id="div_id_form-1-email" class="border px-4 py-2"> <input type="text" name="form-1-email" maxlength="30" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-1-email" /> <small id="hint_id_form-1-email" class="text-gray-600">Insert your email</small> </td> <td id="div_id_form-1-password1" class="border px-4 py-2"> <input type="password" name="form-1-password1" maxlength="30" class="passwordinput w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-1-password1" /> </td> <td id="div_id_form-1-password2" class="border px-4 py-2"> <input type="password" name="form-1-password2" maxlength="30" class="passwordinput w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-1-password2" /> </td> <td id="div_id_form-1-first_name" class="border px-4 py-2"> <input type="text" name="form-1-first_name" maxlength="5" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-1-first_name" /> </td> <td id="div_id_form-1-last_name" class="border px-4 py-2"> <input type="text" name="form-1-last_name" maxlength="5" class="textinput textInput inputtext w-full border border-gray-300 focus:outline-none text-gray-700 px-4 bg-white leading-normal rounded-lg block py-2 appearance-none" id="id_form-1-last_name" /> </td> <td id="div_id_form-1-datetime_field" class="border px-4 py-2"> <input type="text" name="form-1-datetime_field_0" class="dateinput border border-gray-300 text-gray-700 focus:outline-none px-4 mr-2 bg-white focus:outline leading-normal rounded-lg py-2 appearance-none" id="id_form-1-datetime_field_0" /> <input type="text" name="form-1-datetime_field_1" class="timeinput border border-gray-300 text-gray-700 focus:outline-none px-4 mr-2 bg-white focus:outline leading-normal rounded-lg py-2 appearance-none" id="id_form-1-datetime_field_1" /> </td> <td id="div_id_form-1-tos_accepted" class="border px-4 py-2"> <div class="border px-4 py-2"> <div class="relative"> <select class="bg-white focus:outline-none border border-gray-300 rounded-lg py-2 px-4 block w-full appearance-none leading-normal text-gray-700" name="form-1-tos_accepted"> <option value="accepted">Accepted</option> <option value="not_accepted">Not accepted</option> </select> <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700"> <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg> </div> </div> </div> </td> </tr> </tbody> </table> <div class="mt-3"> <div class="form-group"> <div class=""><input type="submit" name="submit" value="submit" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" id="submit-id-submit" /></div> </div> </div> """ self.assertHTMLEqual(html, expected_html)
def test_form_renders_students_text_input(self): form = StudentSearchForm() self.assertIn('form-control', render_crispy_form(form))
def form_invalid(self, form): form_html = render_crispy_form(form) return {'success': False, 'form_html': form_html}
def submitDeposit(request, pk): paper = get_object_or_404(Paper, pk=pk) context = {'status': 'error'} form = PaperDepositForm(data=request.POST) if not form.is_valid(): context['form'] = form.errors return context, 400 # This validation could take place in the form (but we need access to the # paper and user?) repository = form.cleaned_data['radioRepository'] protocol = repository.protocol_for_deposit(paper, request.user) if protocol is None: context['radioRepository'] = _( "This repository cannot be used for this paper.") return context, 400 repositoryForm = protocol.get_bound_form(request.POST) if not repositoryForm.is_valid(): request_context = RequestContext(request) form_html = render_crispy_form(repositoryForm, context=request_context) context['form_html'] = form_html return context, 400 # Store the repository as in the user preferences userprefs = UserPreferences.get_by_user(request.user) userprefs.last_repository = repository userprefs.save(update_fields=['last_repository']) # Check that the paper has been uploaded by the same user pdf = form.cleaned_data['file_id'] if pdf.user != request.user: context['message'] = _('Access to the PDF was denied.') return context, 400 # Submit the paper to the repository path = os.path.join(MEDIA_ROOT, pdf.file.name) # Create initial record d = DepositRecord( paper=paper, user=pdf.user, repository=repository, upload_type=form.cleaned_data['radioUploadType'], file=pdf) d.save() submitResult = protocol.submit_deposit_wrapper(path, repositoryForm) d.request = submitResult.logs if submitResult.status == 'failed': context['message'] = submitResult.message d.save() return context, 400 d.identifier = submitResult.identifier d.additional_info = submitResult.additional_info d.status = submitResult.status d.oairecord = submitResult.oairecord d.save() paper.update_availability() paper.save() paper.update_index() context['status'] = 'success' # TODO change this (we don't need it) context['upload_id'] = d.id return context
def test_formset_layout(self): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset("", 'first_name', 'last_name')) html = render_crispy_form(form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()}) # Check formset fields django_version = django.get_version() if django_version < '1.5': self.assertEqual( html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ), 1) self.assertEqual( html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ), 1) if (django_version >= '1.4' and django_version < '1.4.4') or django_version < '1.3.6': self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ), 1) self.assertEqual( html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ), 1) self.assertEqual( html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ), 1) self.assertEqual(html.count("hidden"), 4) # Check form structure self.assertEqual(html.count('<form'), 1) self.assertEqual( html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) # Check form layout self.assertTrue('Item 1' in html) self.assertTrue('Item 2' in html) self.assertTrue('Item 3' in html) self.assertEqual(html.count('Note for first form only'), 1) if self.current_template_pack == 'uni_form': self.assertEqual(html.count('formRow'), 3) else: self.assertEqual(html.count('row'), 3)
def test_formset_layout(settings): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset( "", 'first_name', 'last_name' ) ) html = render_crispy_form( form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()} ) # Check formset fields hidden_count = 4 # before Django 1.7 added MIN_NUM_FORM_COUNT if django.VERSION < (1, 5): assert html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ) == 1 assert html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ) == 1 assert html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ) == 1 else: assert html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ) == 1 assert html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ) == 1 assert html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ) == 1 if hasattr(forms.formsets, 'MIN_NUM_FORM_COUNT'): assert html.count( 'id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"' ) == 1 hidden_count += 1 assert html.count("hidden") == hidden_count # Check form structure assert html.count('<form') == 1 assert html.count("<input type='hidden' name='csrfmiddlewaretoken'") == 1 assert 'formsets-that-rock' in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse('simpleAction') in html # Check form layout assert 'Item 1' in html assert 'Item 2' in html assert 'Item 3' in html assert html.count('Note for first form only') == 1 if settings.CRISPY_TEMPLATE_PACK == 'uni_form': assert html.count('formRow') == 3 else: assert html.count('row') == 3
def test_formset_layout(settings): SampleFormSet = formset_factory(SampleForm, extra=3) formset = SampleFormSet() helper = FormHelper() helper.form_id = "thisFormsetRocks" helper.form_class = "formsets-that-rock" helper.form_method = "POST" helper.form_action = "simpleAction" helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", "is_company", "email", ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row("password1", "password2"), Fieldset("", "first_name", "last_name"), ) html = render_crispy_form(form=formset, helper=helper, context={"csrf_token": _get_new_csrf_string()}) # Check formset fields assert contains_partial( html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>' ) assert contains_partial( html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial( html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert contains_partial( html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>' ) assert html.count("hidden") == 5 # Check form structure assert html.count("<form") == 1 assert html.count("csrfmiddlewaretoken") == 1 assert "formsets-that-rock" in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse("simpleAction") in html # Check form layout assert "Item 1" in html assert "Item 2" in html assert "Item 3" in html assert html.count("Note for first form only") == 1 if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert html.count("formRow") == 3 elif settings.CRISPY_TEMPLATE_PACK in ("bootstrap3", "bootstrap4"): assert html.count("row") == 3 if settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert html.count("form-group") == 18
def crispy(context, form, helper): """ Renders the form using crispy_forms """ return utils.render_crispy_form(form, helper, context)
def test_formset_layout(settings): SampleFormSet = formset_factory(SampleForm, extra=3) formset = SampleFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset( "", 'first_name', 'last_name' ) ) html = render_crispy_form( form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()} ) # Check formset fields assert contains_partial(html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>' ) assert contains_partial(html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial(html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert contains_partial(html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>' ) assert html.count("hidden") == 5 # Check form structure assert html.count('<form') == 1 assert html.count('csrfmiddlewaretoken') == 1 assert 'formsets-that-rock' in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse('simpleAction') in html # Check form layout assert 'Item 1' in html assert 'Item 2' in html assert 'Item 3' in html assert html.count('Note for first form only') == 1 if settings.CRISPY_TEMPLATE_PACK == 'uni_form': assert html.count('formRow') == 3 elif settings.CRISPY_TEMPLATE_PACK in ('bootstrap3', 'bootstrap4'): assert html.count('row') == 3 if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4': assert html.count('form-group') == 18
def test_multiplecheckboxes(self): test_form = CheckboxesTestForm() html = render_crispy_form(test_form) self.assertEqual(html.count('checked="checked"'), 5)
def reset_gjf(request, upload_form): job_form = JobForm.get_form(request, "{{ name }}") errors = [] strings = [] names = [] for f in upload_form.cleaned_data["files"]: try: parser = fileparser.Log(f) name, _ = os.path.splitext(f.name) td = False if request.REQUEST.get("td_reset"): name += '_TD' td = True strings.append(parser.format_gjf(td=td)) names.append(name) except Exception as e: logger.warn("There was an error when trying to reset a gjf: '%s'" % str(e)) errors.append((f.name, e)) if request.REQUEST.get("gjf_submit"): if not job_form.is_valid(request.method): if request.is_ajax(): upload_form_html = render_crispy_form( upload_form, context=RequestContext(request)) job_form_html = render_crispy_form( job_form, context=RequestContext(request)) a = { "success": False, "job_form_html": job_form_html, "upload_form_html": upload_form_html, } return HttpResponse(json.dumps(a), content_type="application/json") c = { "job_form": job_form, "upload_form": upload_form, } return render(request, "chem/upload_log.html", c) d = dict(job_form.cleaned_data) cred = d.pop("credential") a = cluster.interface.run_jobs(cred, names, strings, **d) a["failed"].extend(errors) do_html = request.REQUEST.get("html", False) if do_html: html = render_to_string("chem/multi_submit.html", a) temp = {"success": True, "html": html} return HttpResponse(json.dumps(temp), content_type="application/json") else: return HttpResponse(json.dumps(a), content_type="application/json") buff = StringIO() zfile = zipfile.ZipFile(buff, 'w', zipfile.ZIP_DEFLATED) for name, string in zip(names, strings): zfile.writestr("%s.gjf" % name, string) if errors: temp = ['%s - %s' % (name, error) for (name, error) in errors] zfile.writestr("errors.txt", '\n'.join(temp)) zfile.close() buff.flush() ret_zip = buff.getvalue() buff.close() response = HttpResponse(ret_zip, content_type="application/zip") response["Content-Disposition"] = "attachment; filename=output.zip" return response
def form_render(form, request): ctx = {} ctx.update(csrf(request)) return render_crispy_form(form, context=ctx)
def game_comment_post(request, next=None, using=None): """ Post a comment. Modified version of the default post view for django_comments """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.get_username() if not data.get('email', ''): data["email"] = request.user.email # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( "Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError) as e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = django_comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: return JsonResponse({ 'form_html': render_crispy_form(form), 'success': False, }) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender=comment.__class__, comment=comment, request=request ) for (receiver, response) in responses: if response == False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send( sender=comment.__class__, comment=comment, request=request ) target.push_notification() return JsonResponse({ 'success': True, })
def test_disable_csrf(): form = SampleForm() helper = FormHelper() helper.disable_csrf = True html = render_crispy_form(form, helper, {'csrf_token': _get_new_csrf_key()}) assert 'csrf' not in html
def render_crispy_form(form, helper=None, context=None): from crispy_forms.utils import render_crispy_form from django.template.context_processors import csrf ctx = {} ctx.update(csrf(context)) return render_crispy_form(form, helper=helper, context=ctx)
def test_bootstrap3_does_add_form_control_class_to_non_multivaluefield(): form = SampleForm() form.helper = FormHelper() form.helper.template_pack = 'bootstrap3' html = render_crispy_form(form) assert 'form-control' in html
def test_formset_with_errors(self): SampleFormSet = formset_factory(ShortCharFieldForm, extra=1, max_num=2, validate_max=True) data = { "name-0-name": "test", "name-INITIAL_FORMS": "0", "name-MIN_NUM_FORMS": "0", "name-MAX_NUM_FORMS": "0", "name-TOTAL_FORMS": "3", } formset = SampleFormSet(data=data, prefix="name") formset.helper = FormHelper() formset.helper.formset_error_title = "Non Form Errors" formset.helper.form_tag = False formset.helper.layout = Layout("email") html = render_crispy_form(formset) expected_html = """ <div> <input type="hidden" name="name-TOTAL_FORMS" value="3" id="id_name-TOTAL_FORMS" /> <input type="hidden" name="name-INITIAL_FORMS" value="0" id="id_name-INITIAL_FORMS" /> <input type="hidden" name="name-MIN_NUM_FORMS" value="0" id="id_name-MIN_NUM_FORMS" /> <input type="hidden" name="name-MAX_NUM_FORMS" value="0" id="id_name-MAX_NUM_FORMS" /> </div> <div class="alert mb-4"> <div class="bg-red-500 text-white font-bold rounded-t px-4 py-2"> Non Form Errors </div> <div class="border border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"> <ul> <li>Please submit 2 or fewer forms.</li> </ul> </div> </div> <div id="div_id_name-0-name" class="mb-3"> <label for="id_name-0-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-0-name" value="test" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-red-500" id="id_name-0-name" /> <p id="error_1_id_name-0-name" class="text-red-500 text-xs italic"><strong>Ensure this value has at most 3 characters (it has 4).</strong></p> </div> <div id="div_id_name-1-name" class="mb-3"> <label for="id_name-1-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-1-name" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-gray-300" id="id_name-1-name" /> </div> <div id="div_id_name-2-name" class="mb-3"> <label for="id_name-2-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-2-name" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-gray-300" id="id_name-2-name" /> </div> """ self.assertHTMLEqual(html, expected_html)