Python django.forms.models.model_to_dict() Examples
The following are 30
code examples of django.forms.models.model_to_dict().
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 also want to check out all available functions/classes of the module
django.forms.models
, or try the search function
.
Example #1
Source File: actions.py From django-idcops with Apache License 2.0 | 7 votes |
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
Source File: actions.py From django-idcops with Apache License 2.0 | 6 votes |
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 #3
Source File: test_static_dynamic_segments.py From wagtail-personalisation with MIT License | 6 votes |
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 #4
Source File: models.py From tom_base with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: import_util.py From zulip with Apache License 2.0 | 6 votes |
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 #6
Source File: operation_env.py From Joy_QA_Platform with Apache License 2.0 | 6 votes |
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 #7
Source File: users.py From zulip with Apache License 2.0 | 6 votes |
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 #8
Source File: export.py From zulip with Apache License 2.0 | 6 votes |
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 #9
Source File: operation_module.py From Joy_QA_Platform with Apache License 2.0 | 6 votes |
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 #10
Source File: import_util.py From zulip with Apache License 2.0 | 6 votes |
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 #11
Source File: actions.py From django-idcops with Apache License 2.0 | 6 votes |
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 #12
Source File: views.py From clist with Apache License 2.0 | 6 votes |
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 #13
Source File: actions.py From django-idcops with Apache License 2.0 | 6 votes |
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 #14
Source File: actions.py From django-idcops with Apache License 2.0 | 6 votes |
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 #15
Source File: views.py From clist with Apache License 2.0 | 6 votes |
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 #16
Source File: slack.py From zulip with Apache License 2.0 | 6 votes |
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 #17
Source File: slack.py From zulip with Apache License 2.0 | 6 votes |
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 #18
Source File: operation_case.py From Joy_QA_Platform with Apache License 2.0 | 6 votes |
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 #19
Source File: xosbase_header.py From xos with Apache License 2.0 | 6 votes |
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 #20
Source File: operation_project.py From Joy_QA_Platform with Apache License 2.0 | 6 votes |
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 #21
Source File: xosbase_header.py From xos with Apache License 2.0 | 6 votes |
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
Source File: views.py From InvenTree with MIT License | 5 votes |
def get_initial(self): """ Get initial data based on the Part to be copied from. """ part = self.get_part_to_copy() if part: initials = model_to_dict(part) else: initials = super(AjaxCreateView, self).get_initial() initials['deep_copy'] = str2bool(InvenTreeSetting.get_setting('part_deep_copy', True)) return initials
Example #23
Source File: import_util.py From zulip with Apache License 2.0 | 5 votes |
def build_zerver_realm(realm_id: int, realm_subdomain: str, time: float, other_product: str) -> List[ZerverFieldsT]: realm = Realm(id=realm_id, date_created=time, name=realm_subdomain, string_id=realm_subdomain, description=f"Organization imported from {other_product}!") auth_methods = [[flag[0], flag[1]] for flag in realm.authentication_methods] realm_dict = model_to_dict(realm, exclude='authentication_methods') realm_dict['authentication_methods'] = auth_methods return[realm_dict]
Example #24
Source File: models.py From cornerwise with MIT License | 5 votes |
def to_dict(self): return model_to_dict(self)
Example #25
Source File: slack.py From zulip with Apache License 2.0 | 5 votes |
def build_customprofile_field(customprofile_field: List[ZerverFieldsT], fields: ZerverFieldsT, custom_profile_field_id: int, realm_id: int, slack_custom_field_name_to_zulip_custom_field_id: ZerverFieldsT) \ -> Tuple[ZerverFieldsT, int]: # The name of the custom profile field is not provided in the slack data # Hash keys of the fields are provided # Reference: https://api.slack.com/methods/users.profile.set for field, value in fields.items(): if field not in slack_custom_field_name_to_zulip_custom_field_id: slack_custom_fields = ['phone', 'skype'] if field in slack_custom_fields: field_name = field else: field_name = f"slack custom field {str(custom_profile_field_id + 1)}" customprofilefield = CustomProfileField( id=custom_profile_field_id, name=field_name, field_type=1, # For now this is defaulted to 'SHORT_TEXT' # Processing is done in the function 'process_customprofilefields' ) customprofilefield_dict = model_to_dict(customprofilefield, exclude=['realm']) customprofilefield_dict['realm'] = realm_id slack_custom_field_name_to_zulip_custom_field_id[field] = custom_profile_field_id custom_profile_field_id += 1 customprofile_field.append(customprofilefield_dict) return slack_custom_field_name_to_zulip_custom_field_id, custom_profile_field_id
Example #26
Source File: mattermost.py From zulip with Apache License 2.0 | 5 votes |
def build_reactions(realm_id: int, total_reactions: List[ZerverFieldsT], reactions: List[ZerverFieldsT], message_id: int, user_id_mapper: IdMapper, zerver_realmemoji: List[ZerverFieldsT]) -> None: realmemoji = {} for realm_emoji in zerver_realmemoji: realmemoji[realm_emoji['name']] = realm_emoji['id'] # For the unicode emoji codes, we use equivalent of # function 'emoji_name_to_emoji_code' in 'zerver/lib/emoji' here for mattermost_reaction in reactions: emoji_name = mattermost_reaction['emoji_name'] username = mattermost_reaction["user"] # Check in unicode emoji if emoji_name in name_to_codepoint: emoji_code = name_to_codepoint[emoji_name] reaction_type = Reaction.UNICODE_EMOJI # Check in realm emoji elif emoji_name in realmemoji: emoji_code = realmemoji[emoji_name] reaction_type = Reaction.REALM_EMOJI else: # nocoverage continue if not user_id_mapper.has(username): continue reaction_id = NEXT_ID('reaction') reaction = Reaction( id=reaction_id, emoji_code=emoji_code, emoji_name=emoji_name, reaction_type=reaction_type) reaction_dict = model_to_dict(reaction, exclude=['message', 'user_profile']) reaction_dict['message'] = message_id reaction_dict['user_profile'] = user_id_mapper.get(username) total_reactions.append(reaction_dict)
Example #27
Source File: models.py From cornerwise with MIT License | 5 votes |
def to_dict(self): d = model_to_dict( self, exclude=["event", "document", "fulltext", "thumbnail"]) if self.thumbnail: d["thumb"] = self.thumbnail.url if self.document: d["url"] = self.document.url return d
Example #28
Source File: models.py From cornerwise with MIT License | 5 votes |
def to_json_dict(self): d = model_to_dict(self, exclude=["created", "proposals"]) d["timezone"] = self.tzname return d
Example #29
Source File: views.py From cornerwise with MIT License | 5 votes |
def proposal_json(proposal, include_images=True, include_attributes=default_attributes, include_events=False, include_documents=True, include_projects=True): pdict = model_to_dict(proposal, exclude=["location", "fulltext"]) pdict["location"] = { "lat": proposal.location.y, "lng": proposal.location.x } if include_documents: pdict["documents"] = [d.to_dict() for d in proposal.documents.all()] if include_images: images = proposal.images.order_by("-priority") # Booleans are considered integers if isinstance(include_images, int) and include_images is not True: images = images[0:include_images] pdict["images"] = [img.to_dict() for img in images] if include_attributes: attributes = proposal.attributes.filter(hidden=False) if include_attributes is not True: attributes = attributes.filter(handle__in=include_attributes) pdict["attributes"] = [a.to_dict() for a in attributes] if include_events: pdict["events"] = [e.to_json_dict() for e in proposal.events.all()] if include_projects and proposal.project: pdict["project"] = proposal.project.to_dict() # TODO: Filter on parcel attributes # TODO: fulltext query return pdict
Example #30
Source File: mixins.py From django-pusherable with BSD 3-Clause "New" or "Revised" License | 5 votes |
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