當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。