当前位置: 首页>>代码示例>>Python>>正文


Python forms.model_to_dict方法代码示例

本文整理汇总了Python中django.forms.model_to_dict方法的典型用法代码示例。如果您正苦于以下问题:Python forms.model_to_dict方法的具体用法?Python forms.model_to_dict怎么用?Python forms.model_to_dict使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.forms的用法示例。


在下文中一共展示了forms.model_to_dict方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: clean

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def clean(self):
        cleaned_data = super(OverwriteOnlyModelFormMixin, self).clean()
        c_cl_data = cleaned_data.copy()
        for field in c_cl_data.keys():
            if self.prefix is not None:
                post_key = '-'.join((self.prefix, field))
            else:
                post_key = field

            if post_key not in list(self.data.keys()) + list(self.files.keys()):
                # value was not posted, thus it should not overwrite any data.
                del cleaned_data[field]

        # only overwrite keys that were actually submitted via POST.
        model_data = model_to_dict(self.instance)
        model_data.update(cleaned_data)
        return model_data 
开发者ID:HackAssistant,项目名称:registration,代码行数:19,代码来源:mixins.py

示例2: to_dict

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def to_dict(self):
        """
        Rather than rendering products based on the instance object,
        we serialize the product to a dictionary, and instead render
        the template based on that.

        NOTE: if you add indirect fields like Foreign/ParentalKey or
              @property definitions, those needs to be added!
        """
        model_dict = model_to_dict(self)
        model_dict['votes'] = self.votes
        model_dict['slug'] = self.slug

        # model_to_dict does NOT capture related fields or @properties!
        model_dict['privacy_policy_links'] = list(self.privacy_policy_links.all())
        model_dict['is_current'] = self.is_current

        return model_dict 
开发者ID:mozilla,项目名称:foundation.mozilla.org,代码行数:20,代码来源:base.py

示例3: __init__

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def __init__(self, form, field, name):
        super().__init__(form, field, name)

        data = self.data if form.is_bound else None
        initial = []
        if self.initial is not None:
            for ini in self.initial:
                if isinstance(ini, Model):
                    initial.append(
                        forms.model_to_dict(
                            ini,
                            fields=field.model_form_class._meta.fields,
                            exclude=field.model_form_class._meta.exclude
                        ))

        self.form_set = field.ArrayFormSet(data, initial=initial, prefix=self.html_name) 
开发者ID:nesdis,项目名称:djongo,代码行数:18,代码来源:fields.py

示例4: test_write_as_owner

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def test_write_as_owner(self):
        dummy_data = model_to_dict(self.dummy_label)
        # Create
        res = self.owner_client.post(reverse('annotationlabel-list'), data=dummy_data, format='json')
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)

        created_id = res.data['id']

        # Partial update
        updated_name = 'Updated name'
        res = self.owner_client.patch(reverse('annotationlabel-detail', args=(created_id,)), data={'name': updated_name}, format='json')
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data['name'], updated_name)

        # Delete
        res = self.owner_client.delete(reverse('annotationlabel-detail', args=(created_id,)))
        self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)

        # Get to deleted item
        res = self.owner_client.get(reverse('annotationlabel-detail', args=(created_id,)))
        self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) 
开发者ID:openlegaldata,项目名称:oldp,代码行数:23,代码来源:test_api.py

示例5: saveModel2File

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def saveModel2File(cls, filename=None, dropPk=True):
        if not filename:
            # 文件名未赋值,则自动产生文件名
            filename = '{}_{}.pkl.gz'.format(cls.__name__, datetime.datetime.now().date())
        from django.forms import model_to_dict
        aobjs = [model_to_dict(aobj) for aobj in cls.objects.all()]
        df = pd.DataFrame(aobjs)
        cls.dropDataframePK(df, dropPk)
        df.to_pickle(filename)
        return filename 
开发者ID:pchaos,项目名称:wanggeService,代码行数:12,代码来源:base.py

示例6: _clone

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def _clone(self):
        # Clone an existing collection.
        original_uid = self.request.data[CLONE_ARG_NAME]
        original_collection = get_object_or_404(Collection, uid=original_uid)
        view_perm = get_perm_name('view', original_collection)
        if not self.request.user.has_perm(view_perm, original_collection):
            raise Http404
        else:
            # Copy the essential data from the original collection.
            original_data = model_to_dict(original_collection)
            cloned_data = {keep_field: original_data[keep_field]
                          for keep_field in COLLECTION_CLONE_FIELDS}
            if original_collection.tag_string:
                cloned_data['tag_string']= original_collection.tag_string

            # Pull any additionally provided parameters/overrides from the
            # request.
            for param in self.request.data:
                cloned_data[param] = self.request.data[param]
            serializer = self.get_serializer(data=cloned_data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)

            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                            headers=headers) 
开发者ID:kobotoolbox,项目名称:kpi,代码行数:28,代码来源:collection.py

示例7: has_changed

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def has_changed(self, initial, data):
        form_set_initial = []
        for init in initial or []:
            form_set_initial.append(
                forms.model_to_dict(
                    init,
                    fields=self.model_form_class._meta.fields,
                    exclude=self.model_form_class._meta.exclude
                )
            )
        form_set = self.ArrayFormSet(data, initial=form_set_initial, prefix=self.name)
        return form_set.has_changed() 
开发者ID:nesdis,项目名称:djongo,代码行数:14,代码来源:fields.py

示例8: default

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def default(self, o):
        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            return timezone.localtime(o).strftime(DATE_TIME_FORMAT)
        elif isinstance(o, datetime.date):
            return o.isoformat()
        elif isinstance(o, datetime.time):
            if is_aware(o):
                raise ValueError("JSON can't represent timezone-aware times.")
            r = o.isoformat()
            if o.microsecond:
                r = r[:12]
            return r
        elif isinstance(o, datetime.timedelta):
            return duration_iso_string(o)
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, uuid.UUID):
            return str(o)
        elif isinstance(o, Promise):
            return six.text_type(o)
        elif isinstance(o, QuerySet):
            return list(o.values())
        elif isinstance(o, Client):
            return model_to_dict(o)
        else:
            return super(JSONEncoder, self).default(o) 
开发者ID:Gerapy,项目名称:Gerapy,代码行数:29,代码来源:encoder.py

示例9: test_create_case_annotation

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def test_create_case_annotation(self):
        dummy_data = model_to_dict(self.dummy_annotation)

        res = self.owner_client.post(reverse('caseannotation-list'), data=dummy_data, format='json')
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)

        created_id = res.data['id']

        # second time -> expect error: duplicated annotation
        res = self.owner_client.post(reverse('caseannotation-list'), data=dummy_data, format='json')
        # print(res.data['label'])
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertTrue('label' in res.data, 'Error should be for `label` field') 
开发者ID:openlegaldata,项目名称:oldp,代码行数:15,代码来源:test_api.py

示例10: test_create_case_annotation_as_guest

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def test_create_case_annotation_as_guest(self):
        dummy_data = model_to_dict(self.dummy_annotation)

        res = self.client.post(reverse('caseannotation-list'), data=dummy_data, format='json')
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) 
开发者ID:openlegaldata,项目名称:oldp,代码行数:7,代码来源:test_api.py

示例11: test_write_as_guest

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def test_write_as_guest(self):
        # Create
        res = self.client.post(reverse('annotationlabel-list'), data=model_to_dict(self.dummy_label), format='json')
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

        # Update
        res = self.client.put(reverse('annotationlabel-detail', args=(2,)))
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

        # Delete
        res = self.client.delete(reverse('annotationlabel-detail', args=(2,)))
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) 
开发者ID:openlegaldata,项目名称:oldp,代码行数:14,代码来源:test_api.py

示例12: live_unread_notification_list

# 需要导入模块: from django import forms [as 别名]
# 或者: from django.forms import model_to_dict [as 别名]
def live_unread_notification_list(request):
    ''' Return a json with a unread notification list '''
    try:
        user_is_authenticated = request.user.is_authenticated()
    except TypeError:  # Django >= 1.11
        user_is_authenticated = request.user.is_authenticated

    if not user_is_authenticated:
        data = {
            'unread_count': 0,
            'unread_list': []
        }
        return JsonResponse(data)

    try:
        # If they don't specify, make it 5.
        num_to_fetch = request.GET.get('max', 5)
        num_to_fetch = int(num_to_fetch)
        # if num_to_fetch is negative, force at least one fetched notifications
        num_to_fetch = max(1, num_to_fetch)
        # put a sane ceiling on the number retrievable
        num_to_fetch = min(num_to_fetch, 100)
    except ValueError:
        num_to_fetch = 5  # If casting to an int fails, just make it 5.

    unread_list = []

    for notification in request.user.notifications.unread()[0:num_to_fetch]:
        struct = model_to_dict(notification)
        struct['slug'] = id2slug(notification.id)
        if notification.actor:
            struct['actor'] = str(notification.actor)
        if notification.target:
            struct['target'] = str(notification.target)
        if notification.action_object:
            struct['action_object'] = str(notification.action_object)
        if notification.data:
            struct['data'] = notification.data
        unread_list.append(struct)
        if request.GET.get('mark_as_read'):
            notification.mark_as_read()
    data = {
        'unread_count': request.user.notifications.unread().count(),
        'unread_list': unread_list
    }
    return JsonResponse(data) 
开发者ID:fresearchgroup,项目名称:Collaboration-System,代码行数:48,代码来源:views.py


注:本文中的django.forms.model_to_dict方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。