Python django.forms.models.model_to_dict() Examples

The following are 30 code examples for showing how to use django.forms.models.model_to_dict(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms.models , or try the search function .

Example 1
Project: django-idcops   Author: Wenvki   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def movedown(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "下架"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.status = 'offline'
            obj.operator = request.user
            obj.units.all().update(actived=True, operator=obj.operator)
            obj.pdus.all().update(actived=True, operator=obj.operator)
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk, action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example 2
Project: django-idcops   Author: Wenvki   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def actived(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "停用"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag="停用",
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example 3
Project: django-idcops   Author: Wenvki   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def reclaim(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "回收"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example 4
Project: django-idcops   Author: Wenvki   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def cancel_reclaim(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "取消回收"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = True
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example 5
Project: django-idcops   Author: Wenvki   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def reoutbound(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "取消出库"
    queryset = queryset.filter(actived=False)
    if not queryset.exists():
        return "查无结果"

    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = True
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None

    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example 6
Project: tom_base   Author: TOMToolkit   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def as_dict(self):
        """
        Returns dictionary representation of attributes, excluding all attributes not associated with the ``type`` of
        this ``Target``.

        :returns: Dictionary of key/value pairs representing target attributes
        :rtype: dict
        """
        if self.type == self.SIDEREAL:
            fields_for_type = SIDEREAL_FIELDS
        elif self.type == self.NON_SIDEREAL:
            fields_for_type = NON_SIDEREAL_FIELDS
        else:
            fields_for_type = GLOBAL_TARGET_FIELDS

        return model_to_dict(self, fields=fields_for_type) 
Example 7
Project: wagtail-personalisation   Author: wagtail   File: test_static_dynamic_segments.py    License: MIT License 6 votes vote down vote up
def form_with_data(segment, *rules):
    model_fields = ['type', 'status', 'count', 'name', 'match_any', 'randomisation_percent']

    class TestSegmentAdminForm(SegmentAdminForm):
        class Meta:
            model = Segment
            fields = model_fields

    data = model_to_dict(segment, model_fields)
    for formset in TestSegmentAdminForm().formsets.values():
        rule_data = {}
        count = 0
        for rule in rules:
            if isinstance(rule, formset.model):
                rule_data = model_to_dict(rule)
                for key, value in rule_data.items():
                    data['{}-{}-{}'.format(formset.prefix, count, key)] = value
                count += 1
        data['{}-INITIAL_FORMS'.format(formset.prefix)] = 0
        data['{}-TOTAL_FORMS'.format(formset.prefix)] = count
    return TestSegmentAdminForm(data) 
Example 8
Project: xos   Author: open-cloud   File: xosbase_header.py    License: Apache License 2.0 6 votes vote down vote up
def serialize_for_messagebus(self):
        """ Serialize the object for posting to messagebus.

            The API serializes ForeignKey fields by naming them <name>_id
            whereas model_to_dict leaves them with the original name. Modify
            the results of model_to_dict to provide the same fieldnames.
        """

        field_types = {}
        for f in self._meta.fields:
            field_types[f.name] = f.get_internal_type()

        fields = model_to_dict(self)
        for k in fields.keys():
            if field_types.get(k, None) == "ForeignKey":
                new_key_name = "%s_id" % k
                if (k in fields) and (new_key_name not in fields):
                    fields[new_key_name] = fields[k]
                    del fields[k]

        return fields 
Example 9
Project: Joy_QA_Platform   Author: JoyMobileDevelopmentTeam   File: operation_case.py    License: Apache License 2.0 6 votes vote down vote up
def case_query(request):
    if request.method == "POST":
        case_id = request.POST.get('id')
        cases = TestCaseInfo.objects.filter(id=case_id)
        moduleid_to_projectid = {}
        moduleid_to_modulename = {}
        if len(cases) == 0:
            return JsonResponse(get_ajax_msg(0, 0, '没有这条数据', {}))
        if cases is not None and len(cases) > 0:
            for case in cases:
                # 所属模块id对应模块名称
                module_id = case.belong_module_id
                module_name = case.belong_module.module_name
                moduleid_to_modulename[str(module_id)] = module_name
                # 所属模块id对应项目id
                project_id = case.belong_module.belong_project_id
                moduleid_to_projectid[str(module_id)] = project_id
        cases = filter_cases_for_user(request.user, cases, AUTH_VIEW)
        data = dataToJson([model_to_dict(i) for i in cases])
        data = json.loads(data)
        return JsonResponse(get_ajax_msg(1, 1, '获取用例信息成功', {'cases': data, 'proInfo': moduleid_to_projectid,
                                                            'moduleInfo': moduleid_to_modulename})) 
Example 10
Project: Joy_QA_Platform   Author: JoyMobileDevelopmentTeam   File: operation_env.py    License: Apache License 2.0 6 votes vote down vote up
def env_search(request):
    if request.method == "POST":
        case_id = request.POST.get('case_id')
        belong_project = 0
        if case_id is not None:
            # 通过测试用例id查询所能用的环境
            cases = TestCaseInfo.objects.filter(id=case_id)
            if len(cases) == 0:
                return JsonResponse(get_ajax_msg(0, 0, '没有这条用例!', {}))
            else:
                case = cases[0]
                belong_project = case.belong_module.belong_project_id
        else:
            belong_project = request.POST.get('project_id')
        if belong_project is None:
            return JsonResponse(get_ajax_msg(0, 0, '数据无效', {}))
        envs = EnvInfo.objects.filter(belong_project_id=belong_project)
        data = dataToJson([model_to_dict(i) for i in envs])
        return JsonResponse(get_ajax_msg(1, 1, '获取用环境息成功', {'envs': data})) 
Example 11
Project: Joy_QA_Platform   Author: JoyMobileDevelopmentTeam   File: operation_module.py    License: Apache License 2.0 6 votes vote down vote up
def module_list(request):
    if request.method == 'GET':
        return render(request, 'api/module_list.html')
    elif request.method == 'POST':
        index = int(request.POST.get('index'))
        project_name_dic = {}
        # 根据用户权限筛选模块
        objects = filter_modules_for_user(request.user, ModuleInfo.objects.order_by('-id'), AUTH_VIEW)
        modules = pagination_for_objects(objects, index)
        if modules is not None and len(modules) > 0:
            for module in modules:
                project_id = module.belong_project_id
                project_name = module.belong_project.project_name
                project_name_dic[str(project_id)] = project_name
        count = len(objects)
        data = dataToJson([model_to_dict(i) for i in modules])
        return JsonResponse(get_ajax_msg(1, 1, '获取模块列表成功', {'modules': data, 'count': count, 'currPage': index,
                                                            'proInfo': project_name_dic})) 
Example 12
Project: Joy_QA_Platform   Author: JoyMobileDevelopmentTeam   File: operation_project.py    License: Apache License 2.0 6 votes vote down vote up
def project_search(request):
    if request.method == "POST":
        project_name = request.POST.get('project_name')
        person_name = request.POST.get('person_name')
        index = int(request.POST.get('index'))
        if len(project_name) == 0 and len(person_name) == 0:
            return JsonResponse(get_ajax_msg(0, 0, '搜索条件无效'))
        else:
            projects = ProjectInfo.objects.all()
            if len(project_name) > 0:
                projects = projects.filter(project_name__contains=project_name)
            if len(person_name) > 0:
                projects = projects.filter(responsible_name__contains=person_name)
        if projects is None:
            return JsonResponse(get_ajax_msg(0, 0, '查询出错'))
        objects = get_objects_for_user(request.user, AUTH_VIEW, projects)  # 根据用户权限筛选项目对象
        projects = pagination_for_objects(objects, index)
        count = objects.count()
        data = dataToJson([model_to_dict(i) for i in projects])
        return JsonResponse(get_ajax_msg(1, 1, '搜索成功', {'projects': data, 'count': count, 'currPage': index})) 
Example 13
Project: zulip   Author: zulip   File: slack.py    License: Apache License 2.0 6 votes vote down vote up
def build_realmemoji(custom_emoji_list: ZerverFieldsT,
                     realm_id: int) -> Tuple[List[ZerverFieldsT],
                                             ZerverFieldsT]:
    zerver_realmemoji = []
    emoji_url_map = {}
    emoji_id = 0
    for emoji_name, url in custom_emoji_list.items():
        if 'emoji.slack-edge.com' in url:
            # Some of the emojis we get from the api have invalid links
            # this is to prevent errors related to them
            realmemoji = RealmEmoji(
                name=emoji_name,
                id=emoji_id,
                file_name=os.path.basename(url),
                deactivated=False)

            realmemoji_dict = model_to_dict(realmemoji, exclude=['realm', 'author'])
            realmemoji_dict['author'] = None
            realmemoji_dict['realm'] = realm_id

            emoji_url_map[emoji_name] = url
            zerver_realmemoji.append(realmemoji_dict)
            emoji_id += 1
    return zerver_realmemoji, emoji_url_map 
Example 14
Project: zulip   Author: zulip   File: slack.py    License: Apache License 2.0 6 votes vote down vote up
def build_customprofilefields_values(slack_custom_field_name_to_zulip_custom_field_id: ZerverFieldsT,
                                     fields: ZerverFieldsT, user_id: int, custom_field_id: int,
                                     custom_field_values: List[ZerverFieldsT]) -> int:
    for field, value in fields.items():
        if value['value'] == "":
            continue
        custom_field_value = CustomProfileFieldValue(
            id=custom_field_id,
            value=value['value'])

        custom_field_value_dict = model_to_dict(custom_field_value,
                                                exclude=['user_profile', 'field'])
        custom_field_value_dict['user_profile'] = user_id
        custom_field_value_dict['field'] = slack_custom_field_name_to_zulip_custom_field_id[field]

        custom_field_values.append(custom_field_value_dict)
        custom_field_id += 1
    return custom_field_id 
Example 15
Project: zulip   Author: zulip   File: import_util.py    License: Apache License 2.0 6 votes vote down vote up
def build_message(topic_name: str, date_sent: float, message_id: int, content: str,
                  rendered_content: Optional[str], user_id: int, recipient_id: int,
                  has_image: bool=False, has_link: bool=False,
                  has_attachment: bool=True) -> ZerverFieldsT:
    zulip_message = Message(
        rendered_content_version=1,  # this is Zulip specific
        date_sent=date_sent,
        id=message_id,
        content=content,
        rendered_content=rendered_content,
        has_image=has_image,
        has_attachment=has_attachment,
        has_link=has_link)
    zulip_message.set_topic_name(topic_name)
    zulip_message_dict = model_to_dict(zulip_message,
                                       exclude=['recipient', 'sender', 'sending_client'])
    zulip_message_dict['sender'] = user_id
    zulip_message_dict['sending_client'] = 1
    zulip_message_dict['recipient'] = recipient_id

    return zulip_message_dict 
Example 16
Project: zulip   Author: zulip   File: import_util.py    License: Apache License 2.0 6 votes vote down vote up
def build_attachment(realm_id: int, message_ids: Set[int],
                     user_id: int, fileinfo: ZerverFieldsT, s3_path: str,
                     zerver_attachment: List[ZerverFieldsT]) -> None:
    """
    This function should be passed a 'fileinfo' dictionary, which contains
    information about 'size', 'created' (created time) and ['name'] (filename).
    """
    attachment_id = NEXT_ID('attachment')

    attachment = Attachment(
        id=attachment_id,
        size=fileinfo['size'],
        create_time=fileinfo['created'],
        is_realm_public=True,
        path_id=s3_path,
        file_name=fileinfo['name'])

    attachment_dict = model_to_dict(attachment,
                                    exclude=['owner', 'messages', 'realm'])
    attachment_dict['owner'] = user_id
    attachment_dict['messages'] = list(message_ids)
    attachment_dict['realm'] = realm_id

    zerver_attachment.append(attachment_dict) 
Example 17
Project: zulip   Author: zulip   File: users.py    License: Apache License 2.0 6 votes vote down vote up
def user_profile_to_user_row(user_profile: UserProfile) -> Dict[str, Any]:
    # What we're trying to do is simulate the user_profile having been
    # fetched from a QuerySet using `.values(*realm_user_dict_fields)`
    # even though we fetched UserProfile objects.  This is messier
    # than it seems.
    #
    # What we'd like to do is just call model_to_dict(user,
    # fields=realm_user_dict_fields).  The problem with this is
    # that model_to_dict has a different convention than
    # `.values()` in its handling of foreign keys, naming them as
    # e.g. `bot_owner`, not `bot_owner_id`; we work around that
    # here.
    #
    # This could be potentially simplified in the future by
    # changing realm_user_dict_fields to name the bot owner with
    # the less readable `bot_owner` (instead of `bot_owner_id`).
    user_row = model_to_dict(user_profile,
                             fields=realm_user_dict_fields + ['bot_owner'])
    user_row['bot_owner_id'] = user_row['bot_owner']
    del user_row['bot_owner']
    return user_row 
Example 18
Project: zulip   Author: zulip   File: export.py    License: Apache License 2.0 6 votes vote down vote up
def fetch_usermessages(realm: Realm,
                       message_ids: Set[int],
                       user_profile_ids: Set[int],
                       message_filename: Path,
                       consent_message_id: Optional[int]=None) -> List[Record]:
    # UserMessage export security rule: You can export UserMessages
    # for the messages you exported for the users in your realm.
    user_message_query = UserMessage.objects.filter(user_profile__realm=realm,
                                                    message_id__in=message_ids)
    if consent_message_id is not None:
        consented_user_ids = get_consented_user_ids(consent_message_id)
        user_profile_ids = user_profile_ids & consented_user_ids
    user_message_chunk = []
    for user_message in user_message_query:
        if user_message.user_profile_id not in user_profile_ids:
            continue
        user_message_obj = model_to_dict(user_message)
        user_message_obj['flags_mask'] = user_message.flags.mask
        del user_message_obj['flags']
        user_message_chunk.append(user_message_obj)
    logging.info("Fetched UserMessages for %s", message_filename)
    return user_message_chunk 
Example 19
Project: clist   Author: aropan   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def process_access_token(request, service, response):
    if response.status_code != requests.codes.ok:
        raise Exception('Response status code not equal ok.')
    try:
        access_token = json.loads(response.text)
    except Exception:
        access_token = dict(parse_qsl(response.text))

    if service.data_header:
        args = model_to_dict(service)
        args.update(access_token)
        headers = json.loads(service.data_header % args)
    else:
        headers = None

    response = requests.get(service.data_uri % access_token, headers=headers)
    return process_data(request, service, access_token, response) 
Example 20
Project: clist   Author: aropan   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def response(request, name):
    service = get_object_or_404(Service, name=name)
    state = request.session.get(service.state_field, None)
    try:
        if state is None or state != request.GET.get('state'):
            raise KeyError('Not found state')
        del request.session['state']
        args = model_to_dict(service)
        args.update(dict(list(request.GET.items())))
        args['redirect_uri'] = settings.HTTPS_HOST_ + reverse('auth:response', args=(name, ))
        if 'code' not in args:
            raise ValueError('Not found code')

        if service.token_post:
            post = json.loads(service.token_post % args)
            response = requests.post(service.token_uri, data=post)
        else:
            url = re.sub('[\n\r]', '', service.token_uri % args)
            response = requests.get(url)
        return process_access_token(request, service, response)
    except Exception as e:
        messages.error(request, "ERROR: {}".format(str(e).strip("'")))
        return signup(request) 
Example 21
Project: xos   Author: opencord   File: xosbase_header.py    License: Apache License 2.0 6 votes vote down vote up
def serialize_for_messagebus(self):
        """ Serialize the object for posting to messagebus.

            The API serializes ForeignKey fields by naming them <name>_id
            whereas model_to_dict leaves them with the original name. Modify
            the results of model_to_dict to provide the same fieldnames.
        """

        field_types = {}
        for f in self._meta.fields:
            field_types[f.name] = f.get_internal_type()

        fields = model_to_dict(self)
        for k in fields.keys():
            if field_types.get(k, None) == "ForeignKey":
                new_key_name = "%s_id" % k
                if (k in fields) and (new_key_name not in fields):
                    fields[new_key_name] = fields[k]
                    del fields[k]

        return fields 
Example 22
Project: pythonjobs.ie   Author: kimeraapp   File: test_views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_create_new_job(self):
        self.job.pk = 0
        params = model_to_dict(self.job)
        response = self.client.post(reverse("job-new"), params)
        self.assertEquals(response.status_code, 302) 
Example 23
Project: django-pusherable   Author: pusher   File: mixins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __object_to_json_serializable(self, object):
        model_dict = model_to_dict(object,
                                   fields=self.pusher_include_model_fields, exclude=self.pusher_exclude_model_fields)
        json_data = json.dumps(model_dict, cls=DjangoJSONEncoder)
        data = json.loads(json_data)
        return data 
Example 24
Project: raveberry   Author: raveberry   File: musiq.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def state_dict(self) -> Dict[str, Any]:
        state_dict = self.base.state_dict()
        current_song: Optional[Dict[str, Any]]
        try:
            current_song = model_to_dict(CurrentSong.objects.get())
        except CurrentSong.DoesNotExist:
            current_song = None
        song_queue = []
        all_songs = self.queue.all()
        if self.base.settings.basic.voting_system:
            all_songs = all_songs.order_by("-votes", "index")
        for song in all_songs:
            song_dict = model_to_dict(song)
            song_dict["duration_formatted"] = song_utils.format_seconds(
                song_dict["duration"]
            )
            song_queue.append(song_dict)

        if state_dict["alarm"]:
            state_dict["current_song"] = {
                "queue_key": -1,
                "manually_requested": False,
                "votes": None,
                "internal_url": "",
                "external_url": "",
                "artist": "Raveberry",
                "title": "ALARM!",
                "duration": 10,
                "created": "",
            }
        else:
            state_dict["current_song"] = current_song
        state_dict["paused"] = self.playback.paused()
        state_dict["progress"] = self.playback.progress()
        state_dict["shuffle"] = self.controller.shuffle
        state_dict["repeat"] = self.controller.repeat
        state_dict["autoplay"] = self.controller.autoplay
        state_dict["volume"] = self.controller.volume
        state_dict["song_queue"] = song_queue
        return state_dict 
Example 25
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, resourceid=None, include_display_values=True):
        datatype_factory = DataTypeFactory()
        nodeid = request.GET.get("nodeid", None)
        search_term = request.GET.get("term", None)
        permitted_tiles = []
        perm = "read_nodegroup"
        tiles = models.TileModel.objects.filter(resourceinstance_id=resourceid)
        if nodeid is not None:
            node = models.Node.objects.get(pk=nodeid)
            tiles = tiles.filter(nodegroup=node.nodegroup)

        for tile in tiles:
            if request.user.has_perm(perm, tile.nodegroup):
                tile = Tile.objects.get(pk=tile.tileid)
                tile.filter_by_perm(request.user, perm)
                tile_dict = model_to_dict(tile)
                if include_display_values:
                    tile_dict["display_values"] = []
                    for node in models.Node.objects.filter(nodegroup=tile.nodegroup):
                        if str(node.nodeid) in tile.data:
                            datatype = datatype_factory.get_instance(node.datatype)
                            display_value = datatype.get_display_value(tile, node)
                            if search_term is not None and search_term in display_value:
                                tile_dict["display_values"].append({"value": display_value, "label": node.name, "nodeid": node.nodeid})
                            elif search_term is None:
                                tile_dict["display_values"].append({"value": display_value, "label": node.name, "nodeid": node.nodeid})

                if search_term is None:
                    permitted_tiles.append(tile_dict)
                elif len(tile_dict["display_values"]) > 0:
                    permitted_tiles.append(tile_dict)
        return JSONResponse({"tiles": permitted_tiles}) 
Example 26
Project: arches   Author: archesproject   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def save(self):
        from arches.app.search.search_engine_factory import SearchEngineFactory

        se = SearchEngineFactory().create()
        if not self.created:
            self.created = datetime.datetime.now()
        self.modified = datetime.datetime.now()
        document = model_to_dict(self)
        se.index_data(index="resource_relations", body=document, idfield="resourcexid")
        super(ResourceXResource, self).save() 
Example 27
Project: adventurelookup-backend   Author: AdventureLookup   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request):
        data = model_to_dict(self.adventure)
        return JsonResponse(data) 
Example 28
Project: resolwe   Author: genialis   File: prepare.py    License: Apache License 2.0 5 votes vote down vote up
def extend_settings(self, data_id, files, secrets):
        """Extend the settings the manager will serialize.

        :param data_id: The :class:`~resolwe.flow.models.Data` object id
            being prepared for.
        :param files: The settings dictionary to be serialized. Keys are
            filenames, values are the objects that will be serialized
            into those files. Standard filenames are listed in
            ``resolwe.flow.managers.protocol.ExecutorFiles``.
        :param secrets: Secret files dictionary describing additional secret
            file content that should be created and made available to
            processes with special permissions. Keys are filenames, values
            are the raw strings that should be written into those files.
        """
        data = Data.objects.select_related("process").get(pk=data_id)

        files[ExecutorFiles.DJANGO_SETTINGS].update(
            {
                "USE_TZ": settings.USE_TZ,
                "FLOW_EXECUTOR_TOOLS_PATHS": self.get_tools_paths(),
            }
        )
        files[ExecutorFiles.DATA] = model_to_dict(data)
        files[ExecutorFiles.STORAGE_LOCATION] = model_to_dict(data.location)
        files[ExecutorFiles.STORAGE_LOCATION][
            "url"
        ] = data.location.default_storage_location.url
        files[ExecutorFiles.PROCESS] = model_to_dict(data.process)
        files[ExecutorFiles.PROCESS][
            "resource_limits"
        ] = data.process.get_resource_limits()

        # Add secrets if the process has permission to read them.
        secrets.update(data.resolve_secrets()) 
Example 29
Project: longclaw   Author: JamesRamm   File: tests.py    License: MIT License 5 votes vote down vote up
def test_address_form(self):
        form = AddressForm(data=model_to_dict(self.address))
        self.assertTrue(form.is_valid(), form.errors.as_json()) 
Example 30
Project: django-idcops   Author: Wenvki   File: edit.py    License: Apache License 2.0 5 votes vote down vote up
def form_valid(self, form):
        form.instance.operator = self.request.user
        if 'onidc' not in form.cleaned_data:
            form.instance.onidc = self.request.user.onidc
        d1 = form.initial
        message = json.dumps(form.changed_data)
        response = super(EditModelView, self).form_valid(form)
        d2 = model_to_dict(construct_instance(form, self.object))
        diffs = diff_dict(make_dict(d1), make_dict(d2))
        content = json.dumps(diffs)
        log_action(
            user_id=self.request.user.pk,
            content_type_id=get_content_type_for_model(self.object, True).pk,
            object_id=self.object.pk,
            action_flag="修改", message=message, content=content
        )
        if self.model_name == 'online':
            verify = Thread(target=device_post_save, args=(self.object.pk,))
            verify.start()
        if self.request.is_ajax():
            data = {
                'message': "Successfully submitted form data.",
                'data': form.cleaned_data
            }
            return JsonResponse(data)
        else:
            return response