Ejemplo n.º 1
0
def profiles_create(request, board):
    board_type = get_object_or_404(BoardType, pk=board)
    if request.method == "GET":
        return render(request, "scoreboard/settings_create.html", {
            "detailform": SettingsDetailForm(initial={'isActive': 1}),
            "JSONform": JSONSchemaForm(schema=board_type.schema(), options=services.form_options({}), ajax=True),
            "boardtype": board,
        })

    if request.method == "POST":
        detailform = SettingsDetailForm(request.POST)
        detailform.is_valid()
        try:
            # The request data for the config json must be encoded and then decoded again as below due to a BOM error.
            # Without this the form submissions are saved as slash escaped strings... but why? Possibly due to jsonforms encoding methods.
            new_config = json.loads(request.POST['json'].encode().decode('utf-8-sig'))
            name = detailform.cleaned_data['name']
            isActive = detailform.cleaned_data['isActive']
            new_settings = Settings.objects.create(name=name, isActive=isActive, config=new_config, boardType=board_type)
            new_settings.save()

            message = "Your profile has been saved." + notes[isActive]
            messages.success(request, message)

            return HttpResponseRedirect(reverse("profiles_list"), {"message": message, })

        except (Exception, ValidationError, ValueError, FieldError) as e:
            message = "Warning. ({})".format(e)
            messages.info(request, message)
            return render(request, "scoreboard/settings_create.html", {
                "detailform": detailform,
                "JSONform": JSONSchemaForm(schema=board_type.schema(), options=services.form_options(new_config), ajax=True),
                "boardtype": board,
                "message": message,
            })
Ejemplo n.º 2
0
    def test_valid_data_for_schema(self):

        form_data = {'json': json.dumps(self.test_json)}
        form = JSONSchemaForm(schema=self.schema,
                              options=self.options,
                              data=form_data)
        self.assertTrue(form.is_valid())
Ejemplo n.º 3
0
    def test_valid_data_with_schema_file_dir_setting(self):

        form_data = {'json': json.dumps(self.test_json)}
        form = JSONSchemaForm(
            schema='tests/testapp/staticfiles/test_schema.json',
            options=self.options,
            data=form_data)
        self.assertTrue(form.is_valid())
Ejemplo n.º 4
0
    def test_invalid_json(self):

        form_data = {'json': '{\"yeah\": \"yeah}'}
        form = JSONSchemaForm(schema=self.schema,
                              options=self.options,
                              data=form_data)

        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['json'], [u"Invalid JSON"])
Ejemplo n.º 5
0
    def test_no_validate_setting(self):

        test_json = {
            'color': 'red',
            'number': 'one',
        }
        form_data = {'json': json.dumps(test_json)}
        form = JSONSchemaForm(schema=self.schema,
                              options=self.options,
                              data=form_data)
        self.assertTrue(form.is_valid())
Ejemplo n.º 6
0
    def test_invalid_data_for_schema(self):

        test_json = {
            'color': 'red',
            'number': 'one',
        }
        form_data = {'json': json.dumps(test_json)}
        form = JSONSchemaForm(schema=self.schema,
                              options=self.options,
                              data=form_data)

        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['json'],
                         [u"\'one\' is not of type \'integer\'"])
Ejemplo n.º 7
0
    def test_render_valid_data(self):

        form_data = {'json': json.dumps(self.test_json)}
        form = JSONSchemaForm(schema=self.schema,
                              options=self.options,
                              data=form_data)
        output = form.as_p()

        # Check that div with class editor_holder was rendered
        self.assertNotEqual(output.find('class=\"editor_holder\"'), -1)

        media = str(form.media)

        # Check that the media was included correctly
        self.assertNotEqual(media.find('jsoneditor.min.js'), -1)
        self.assertNotEqual(media.find('jsoneditor_init.js'), -1)
Ejemplo n.º 8
0
    def test_invalid_schema_file(self):

        form = JSONSchemaForm(options=self.options,
                              schema='very/real/file.json')
        self.assertFalse(form.is_valid())
Ejemplo n.º 9
0
def profiles(request, id):
    if request.method == "GET":
        profile = get_object_or_404(Settings, pk=id)
        if profile.id != 1 or profile.name.lower() != "default":
            return render(request, "scoreboard/settings_edit.html", {
                "detailform": SettingsDetailForm(initial={"name":profile.name, "isActive": profile.isActive}),
                "JSONform": JSONSchemaForm(schema=profile.boardType.schema(), options=services.form_options(profile.config), ajax=True),
                "profile_id": profile.pk,
                "profile_name": profile.name
            })
        else:
            messages.error(request, "Cannot edit the default profile!")
            return HttpResponseRedirect(reverse('profiles_list'))

    elif request.method == "PUT":
        profile = get_object_or_404(Settings, pk=id)
        data = json.loads(request.body)

        if data.get("activated"):
            try:
                if not profile.isActive:
                    profile.isActive = True
                    profile.save(update_fields=['isActive'])
                    messages.success(request, "\"" + profile.name + "\" activated.")
                    return JsonResponse({
                        "activated": True
                    }, status=202)
            except (ValueError, ValidationError) as error:
                logger.error(str(error))
                return JsonResponse({
                    "activated": False,
                    "profile": profile.name,
                    "error": str(error)
                }, status=404)

        if data.get("backup"):
            try:
                path = profile.save_to_file().strip()
                return JsonResponse({
                    "backup": True,
                    "path": path
                }, status=202)
            except (ValueError, ValidationError) as error:
                return JsonResponse({
                    "backup": False,
                    "error": str(error)
                }, status=400)

        if data.get("delete"):
            try:
                name = profile.name
                profile.delete()
                message = "\"" + name + "\" deleted successfully."
                messages.success(request, message)
                return JsonResponse({
                    "delete": True,
                }, status=202)
            except Exception as e:
                logger.exception(str(e))
                return JsonResponse({
                    "delete": False,
                    "profile": profile.name,
                }, status=400)

    elif request.method == "POST":
        try:
            profile = get_object_or_404(Settings, pk=id)
            detailform = SettingsDetailForm(request.POST)
            new_config = json.loads(request.POST['json'])

            if detailform.is_valid():
                profile.name = detailform.cleaned_data['name']
                profile.isActive = detailform.cleaned_data['isActive']
                profile.config = new_config
                profile.save(update_fields=['config', 'name', 'isActive'])
                message = "Your profile has been updated." + notes[profile.isActive]
                messages.success(request, message)
                return HttpResponseRedirect(reverse("profiles_list"), {"message": message, })
            
            errors = detailform.non_field_errors

            if "__all__" in detailform.non_field_errors:
                errors = detailform.non_field_errors["__all__"]
            
            messages.error(request, errors)
            logger.error(str(errors))
            return render(request, "scoreboard/settings_create.html", {
                "detailform": detailform,
                "JSONform": JSONSchemaForm(schema=profile.boardType.schema(), options=services.form_options(profile.config), ajax=True),
                "boardtype": profile.boardType.board,
                "message": errors
            })

        except (Exception, ValidationError, ValueError, FieldError) as e:
            message = "Warning. ({})".format(e)
            messages.info(request, message)
            logger.exception(message)
            return render(request, "scoreboard/settings_create.html", {
                "detailform": detailform,
                "JSONform": JSONSchemaForm(schema=profile.boardType.schema(), options=services.form_options(profile.config), ajax=True),
                "boardtype": profile.boardType.board,
                "message": message
            })