Beispiel #1
0
    def forms(self, request, **kwargs):
        """Add a form to a project or list forms for the project.

        The request key `xls_file` holds the XLSForm file object.
        """
        project = get_object_or_404(Project, pk=kwargs.get('pk'))
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(project, 'modified')))
        if request.method.upper() == 'POST':
            survey = utils.publish_project_xform(request, project)

            if isinstance(survey, XForm):
                xform = XForm.objects.get(pk=survey.pk)
                serializer = XFormSerializer(xform,
                                             context={'request': request})

                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            return Response(survey, status=status.HTTP_400_BAD_REQUEST)

        project_xforms = project.projectxform_set.values('xform')
        xforms = XForm.objects.filter(pk__in=project_xforms)
        serializer = XFormSerializer(xforms,
                                     context={'request': request},
                                     many=True)

        return Response(serializer.data)
Beispiel #2
0
    def retrieve(self, request, *args, **kwargs):
        data_id = str(kwargs.get('dataid'))
        _format = kwargs.get('format')

        if not data_id.isdigit():
            raise ParseError(_(u"Data ID should be an integer"))

        try:
            instance = Instance.objects.get(pk=data_id)
            self.headers = merge_dicts(
                self.headers,
                last_modified_header(get_date(instance, 'modified')))

            if _format == 'json' or _format is None:
                return Response(instance.json)
            elif _format == 'xml':
                return Response(instance.xml)
            else:
                raise ParseError(
                    _(u"'%(_format)s' format unknown or not implemented!" %
                      {'_format': _format}))
        except Instance.DoesNotExist:
            raise ParseError(
                _(u"data with id '%(data_id)s' not found!" %
                  {'data_id': data_id}))
Beispiel #3
0
    def retrieve(self, request, *args, **kwargs):
        data_id = str(kwargs.get('dataid'))
        _format = kwargs.get('format')

        if not data_id.isdigit():
            raise ParseError(_(u"Data ID should be an integer"))

        try:
            instance = Instance.objects.get(pk=data_id)
            self.headers = merge_dicts(
                self.headers,
                last_modified_header(get_date(instance, 'modified')))

            if _format == 'json' or _format is None:
                return Response(instance.json)
            elif _format == 'xml':
                return Response(instance.xml)
            else:
                raise ParseError(
                    _(u"'%(_format)s' format unknown or not implemented!" %
                      {'_format': _format})
                )
        except Instance.DoesNotExist:
            raise ParseError(
                _(u"data with id '%(data_id)s' not found!" %
                  {'data_id': data_id})
            )
Beispiel #4
0
    def labels(self, request, *args, **kwargs):
        http_status = status.HTTP_400_BAD_REQUEST
        instance = self.get_object()
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(instance, 'modified')))

        if request.method == 'POST':
            if add_tags_to_instance(request, instance):
                http_status = status.HTTP_201_CREATED

        tags = instance.tags
        label = kwargs.get('label', None)

        if request.method == 'GET' and label:
            data = [
                tag['name'] for tag in tags.filter(name=label).values('name')
            ]

        elif request.method == 'DELETE' and label:
            count = tags.count()
            tags.remove(label)

            # Accepted, label does not exist hence nothing removed
            http_status = status.HTTP_200_OK if count == tags.count() \
                else status.HTTP_404_NOT_FOUND

            data = list(tags.names())
        else:
            data = list(tags.names())

        if request.method == 'GET':
            http_status = status.HTTP_200_OK

        return Response(data, status=http_status)
Beispiel #5
0
    def labels(self, request, *args, **kwargs):
        http_status = status.HTTP_400_BAD_REQUEST
        instance = self.get_object()
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(instance, 'modified')))

        if request.method == 'POST':
            if add_tags_to_instance(request, instance):
                http_status = status.HTTP_201_CREATED

        tags = instance.tags
        label = kwargs.get('label', None)

        if request.method == 'GET' and label:
            data = [tag['name'] for tag in
                    tags.filter(name=label).values('name')]

        elif request.method == 'DELETE' and label:
            count = tags.count()
            tags.remove(label)

            # Accepted, label does not exist hence nothing removed
            http_status = status.HTTP_200_OK if count == tags.count() \
                else status.HTTP_404_NOT_FOUND

            data = list(tags.names())
        else:
            data = list(tags.names())

        if request.method == 'GET':
            http_status = status.HTTP_200_OK

        return Response(data, status=http_status)
Beispiel #6
0
    def forms(self, request, **kwargs):
        """Add a form to a project or list forms for the project.

        The request key `xls_file` holds the XLSForm file object.
        """
        project = get_object_or_404(Project, pk=kwargs.get('pk'))
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(project, 'modified')))
        if request.method.upper() == 'POST':
            survey = utils.publish_project_xform(request, project)

            if isinstance(survey, XForm):
                xform = XForm.objects.get(pk=survey.pk)
                serializer = XFormSerializer(
                    xform, context={'request': request})

                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            return Response(survey, status=status.HTTP_400_BAD_REQUEST)

        project_xforms = project.projectxform_set.values('xform')
        xforms = XForm.objects.filter(pk__in=project_xforms)
        serializer = XFormSerializer(xforms, context={'request': request},
                                     many=True)

        return Response(serializer.data)
Beispiel #7
0
    def retrieve(self, request, *args, **kwargs):
        xform = self.get_object()
        serializer = self.get_serializer(xform)
        dd = xform.data_dictionary()

        field_name = request.QUERY_PARAMS.get('field_name')
        fields = request.QUERY_PARAMS.get('fields')
        fmt = kwargs.get('format')

        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(xform, 'modified')))
        if fields:
            if fmt is not None and fmt != 'json':
                raise ParseError("Error: only JSON format supported.")

            xform = self.get_object()
            self.headers['Last-Modified'] = get_date(xform, 'modified')
            context = self.get_serializer_context()
            serializer = FieldsChartSerializer(instance=xform, context=context)

            return Response(serializer.data)

        if field_name:
            # check if its the special _submission_time META
            if field_name == common_tags.SUBMISSION_TIME:
                field = common_tags.SUBMISSION_TIME
            else:
                # use specified field to get summary
                fields = filter(lambda f: f.name == field_name,
                                [e for e in dd.survey_elements])

                if len(fields) == 0:
                    raise Http404("Field %s does not not exist on the form" %
                                  field_name)

                field = fields[0]

            data = build_chart_data_for_field(xform, field)

            if request.accepted_renderer.format == 'json':
                xform = xform.pk
            elif request.accepted_renderer.format == 'html' and 'data' in data:
                for item in data['data']:
                    if isinstance(item[field_name], list):
                        item[field_name] = u', '.join(item[field_name])

            data.update({'xform': xform})

            return Response(data, template_name='chart_detail.html')

        if fmt != 'json' and field_name is None:
            raise ParseError("Not supported")

        data = serializer.data
        data["fields"] = {}
        for field in dd.survey_elements:
            field_url = get_form_field_chart_url(data["url"], field.name)
            data["fields"][field.name] = field_url

        return Response(data)
Beispiel #8
0
    def starred(self, request, *args, **kwargs):
        """Return projects starred for this user."""
        user_profile = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(user_profile, 'joined')))
        user = user_profile.user
        projects = user.project_set.all()
        serializer = ProjectSerializer(projects,
                                       context={'request': request},
                                       many=True)

        return Response(data=serializer.data)
Beispiel #9
0
    def starred(self, request, *args, **kwargs):
        """Return projects starred for this user."""
        user_profile = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(user_profile, 'joined')))
        user = user_profile.user
        projects = user.project_set.all()
        serializer = ProjectSerializer(projects,
                                       context={'request': request},
                                       many=True)

        return Response(data=serializer.data)
Beispiel #10
0
    def star(self, request, *args, **kwargs):
        user = request.user
        project = get_object_or_404(Project, pk=kwargs.get('pk'))
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(project, 'modified')))

        if request.method == 'DELETE':
            project.user_stars.remove(user)
        elif request.method == 'POST':
            project.user_stars.add(user)
        elif request.method == 'GET':
            users = project.user_stars.values('pk')
            user_profiles = UserProfile.objects.filter(user__in=users)
            serializer = UserProfileSerializer(user_profiles,
                                               context={'request': request},
                                               many=True)

            return Response(serializer.data)

        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #11
0
    def star(self, request, *args, **kwargs):
        user = request.user
        project = get_object_or_404(Project, pk=kwargs.get('pk'))
        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(project, 'modified')))

        if request.method == 'DELETE':
            project.user_stars.remove(user)
        elif request.method == 'POST':
            project.user_stars.add(user)
        elif request.method == 'GET':
            users = project.user_stars.values('pk')
            user_profiles = UserProfile.objects.filter(user__in=users)
            serializer = UserProfileSerializer(user_profiles,
                                               context={'request': request},
                                               many=True)

            return Response(serializer.data)

        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #12
0
    def retrieve(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(self.object, 'modified')))

        if isinstance(request.accepted_renderer, MediaFileRenderer) \
                and self.object.media_file is not None:
            data = self.object.media_file.read()

            return Response(data, content_type=self.object.mimetype)

        filename = request.QUERY_PARAMS.get('filename')
        serializer = self.get_serializer(self.object)

        if filename:
            if filename == self.object.media_file.name:
                return Response(serializer.get_download_url(self.object))
            else:
                raise Http404(_("Filename '%s' not found." % filename))

        return Response(serializer.data)
Beispiel #13
0
    def retrieve(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(self.object, 'modified')))

        if isinstance(request.accepted_renderer, MediaFileRenderer) \
                and self.object.media_file is not None:
            data = self.object.media_file.read()

            return Response(data, content_type=self.object.mimetype)

        filename = request.QUERY_PARAMS.get('filename')
        serializer = self.get_serializer(self.object)

        if filename:
            if filename == self.object.media_file.name:
                return Response(serializer.get_download_url(self.object))
            else:
                raise Http404(_("Filename '%s' not found." % filename))

        return Response(serializer.data)
Beispiel #14
0
    def enketo(self, request, *args, **kwargs):
        self.object = self.get_object()
        data = {}
        if isinstance(self.object, XForm):
            raise ParseError(_(u"Data id not provided."))
        elif(isinstance(self.object, Instance)):
            self.headers = merge_dicts(
                self.headers,
                last_modified_header(get_date(self.object, 'modified')))
            if request.user.has_perm("change_xform", self.object.xform):
                return_url = request.QUERY_PARAMS.get('return_url')
                if not return_url:
                    raise ParseError(_(u"return_url not provided."))

                try:
                    data["url"] = get_enketo_edit_url(
                        request, self.object, return_url)
                except EnketoError as e:
                    data['detail'] = "{}".format(e)
            else:
                raise PermissionDenied(_(u"You do not have edit permissions."))

        return Response(data=data)
Beispiel #15
0
    def enketo(self, request, *args, **kwargs):
        self.object = self.get_object()
        data = {}
        if isinstance(self.object, XForm):
            raise ParseError(_(u"Data id not provided."))
        elif (isinstance(self.object, Instance)):
            self.headers = merge_dicts(
                self.headers,
                last_modified_header(get_date(self.object, 'modified')))
            if request.user.has_perm("change_xform", self.object.xform):
                return_url = request.QUERY_PARAMS.get('return_url')
                if not return_url:
                    raise ParseError(_(u"return_url not provided."))

                try:
                    data["url"] = get_enketo_edit_url(request, self.object,
                                                      return_url)
                except EnketoError as e:
                    data['detail'] = "{}".format(e)
            else:
                raise PermissionDenied(_(u"You do not have edit permissions."))

        return Response(data=data)
Beispiel #16
0
    def members(self, request, *args, **kwargs):
        organization = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(organization, 'joined')))
        status_code = status.HTTP_200_OK
        data = []
        username = request.DATA.get('username') or request.QUERY_PARAMS.get(
            'username')

        if request.method in ['DELETE', 'POST', 'PUT'] and not username:
            status_code = status.HTTP_400_BAD_REQUEST
            data = {'username': [_(u"This field is required.")]}
        elif request.method == 'POST':
            data, status_code = _add_username_to_organization(
                organization, username)
        elif request.method == 'PUT':
            role = request.DATA.get('role')
            role_cls = ROLES.get(role)

            if not role or not role_cls:
                status_code = status.HTTP_400_BAD_REQUEST
                message = (_(u"'%s' is not a valid role." %
                             role) if role else _(u"This field is required."))
                data = {'role': [message]}
            else:
                _update_username_role(organization, username, role_cls)
        elif request.method == 'DELETE':
            data, status_code = _remove_username_to_organization(
                organization, username)

        if status_code in [status.HTTP_200_OK, status.HTTP_201_CREATED]:
            members = get_organization_members(organization)
            data = [u.username for u in members]

        return Response(data, status=status_code)
    def members(self, request, *args, **kwargs):
        organization = self.get_object()
        self.headers = merge_dicts(
            self.headers,
            last_modified_header(get_date(organization, 'joined')))
        status_code = status.HTTP_200_OK
        data = []
        username = request.DATA.get('username') or request.QUERY_PARAMS.get(
            'username')

        if request.method in ['DELETE', 'POST', 'PUT'] and not username:
            status_code = status.HTTP_400_BAD_REQUEST
            data = {'username': [_(u"This field is required.")]}
        elif request.method == 'POST':
            data, status_code = _add_username_to_organization(
                organization, username)
        elif request.method == 'PUT':
            role = request.DATA.get('role')
            role_cls = ROLES.get(role)

            if not role or not role_cls:
                status_code = status.HTTP_400_BAD_REQUEST
                message = (_(u"'%s' is not a valid role." % role) if role
                           else _(u"This field is required."))
                data = {'role': [message]}
            else:
                _update_username_role(organization, username, role_cls)
        elif request.method == 'DELETE':
            data, status_code = _remove_username_to_organization(
                organization, username)

        if status_code in [status.HTTP_200_OK, status.HTTP_201_CREATED]:
            members = get_organization_members(organization)
            data = [u.username for u in members]

        return Response(data, status=status_code)
Beispiel #18
0
    def retrieve(self, request, *args, **kwargs):
        xform = self.get_object()
        serializer = self.get_serializer(xform)
        dd = xform.data_dictionary()

        field_name = request.QUERY_PARAMS.get('field_name')
        fields = request.QUERY_PARAMS.get('fields')
        fmt = kwargs.get('format')

        self.headers = merge_dicts(
            self.headers, last_modified_header(get_date(xform, 'modified')))
        if fields:
            if fmt is not None and fmt != 'json':
                raise ParseError("Error: only JSON format supported.")

            xform = self.get_object()
            self.headers['Last-Modified'] = get_date(xform, 'modified')
            context = self.get_serializer_context()
            serializer = FieldsChartSerializer(instance=xform, context=context)

            return Response(serializer.data)

        if field_name:
            # check if its the special _submission_time META
            if field_name == common_tags.SUBMISSION_TIME:
                field = common_tags.SUBMISSION_TIME
            else:
                # use specified field to get summary
                fields = filter(
                    lambda f: f.name == field_name,
                    [e for e in dd.survey_elements])

                if len(fields) == 0:
                    raise Http404(
                        "Field %s does not not exist on the form" % field_name)

                field = fields[0]

            data = build_chart_data_for_field(xform, field)

            if request.accepted_renderer.format == 'json':
                xform = xform.pk
            elif request.accepted_renderer.format == 'html' and 'data' in data:
                for item in data['data']:
                    if isinstance(item[field_name], list):
                        item[field_name] = u', '.join(item[field_name])

            data.update({
                'xform': xform
            })

            return Response(data, template_name='chart_detail.html')

        if fmt != 'json' and field_name is None:
            raise ParseError("Not supported")

        data = serializer.data
        data["fields"] = {}
        for field in dd.survey_elements:
            field_url = get_form_field_chart_url(data["url"], field.name)
            data["fields"][field.name] = field_url

        return Response(data)