Python django.forms.model_to_dict() Examples

The following are 12 code examples for showing how to use django.forms.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 , or try the search function .

Example 1
Project: registration   Author: HackAssistant   File: mixins.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: foundation.mozilla.org   Author: mozilla   File: base.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 
Example 3
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 4
Project: oldp   Author: openlegaldata   File: test_api.py    License: MIT License 6 votes vote down vote up
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) 
Example 5
Project: wanggeService   Author: pchaos   File: base.py    License: MIT License 5 votes vote down vote up
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 
Example 6
Project: kpi   Author: kobotoolbox   File: collection.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example 7
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example 8
Project: Gerapy   Author: Gerapy   File: encoder.py    License: MIT License 5 votes vote down vote up
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) 
Example 9
Project: oldp   Author: openlegaldata   File: test_api.py    License: MIT License 5 votes vote down vote up
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') 
Example 10
Project: oldp   Author: openlegaldata   File: test_api.py    License: MIT License 5 votes vote down vote up
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) 
Example 11
Project: oldp   Author: openlegaldata   File: test_api.py    License: MIT License 5 votes vote down vote up
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) 
Example 12
Project: Collaboration-System   Author: fresearchgroup   File: views.py    License: GNU General Public License v2.0 4 votes vote down vote up
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)