django.forms.model_to_dict - python examples

Here are the examples of the python api django.forms.model_to_dict taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

17 Examples 7

3 View Complete Implementation : json_ex.py
Copyright GNU General Public License v3.0
Author : banxi1988
    def default(self, o):
        # TypeError: Object of type 'ImageFieldFile' is not JSON serializable
        if callable(getattr(o, "to_dict",None)):
            return o.to_dict()
        elif isinstance(o, FieldFile):
            if o:
                return o.url
            else:
                return None
        elif isinstance(o, (StrEnum, IntEnum)):
            return o.value
        elif isinstance(o, db.models.Model):
            return model_to_dict(o)
        return super().default(o)

3 View Complete Implementation : mixins.py
Copyright GNU General Public License v3.0
Author : banxi1988
    def to_dict(self, fields=None, exclude=None):
        """
           Return a dict containing the data in ``instance`` suitable for pasting as
           a Form's ``initial`` keyword argument.

           ``fields`` is an optional list of field names. If provided, return only the
           named.

           ``exclude`` is an optional list of field names. If provided, exclude the
           named from the returned dict, even if they are listed in the ``fields``
           argument. `_deleted_at` are exclude anyway
        """
        if not exclude:
            exclude = ["_deleted_at"]
        else:
            exclude.append("_deleted_at")

        return model_to_dict(self, fields, exclude)

3 View Complete Implementation : storage.py
Copyright MIT License
Author : catcombo
    def fetch_all(self, ordering=None):
        qs = Storage.objects.annotate(
            anon_calls_ratio=ExpressionWrapper(100.0 * F("anon_calls") / F("total_calls"), output_field=FloatField()),
            cache_hits_ratio=ExpressionWrapper(100.0 * F("cache_hits") / F("total_calls"), output_field=FloatField()),
            sql_count_per_call=ExpressionWrapper(F("sql_total_count") / F("total_calls"), output_field=IntegerField()),
            sql_time_ratio=ExpressionWrapper(100.0 * F("sql_total_time") / F("total_time"), output_field=FloatField()),
            time_per_call=ExpressionWrapper(F("total_time") / F("total_calls"), output_field=FloatField()),
        )

        if ordering:
            qs = qs.order_by(*ordering)

        return [ViewProfiler(**model_to_dict(item)) for item in qs]

3 View Complete Implementation : test_storage.py
Copyright MIT License
Author : catcombo
    def test_add(self):
        self.storage.add(
            view_name="app.view_name", method="GET", is_anon_call=True, is_cache_hit=True,
            sql_time=2, sql_count=3, view_execution_time=4,
        )
        entries = self.storage.fetch_all()

        self.astertEqual(len(entries), 1)
        self.astertDictEqual(dict(
            view_name="app.view_name", method="GET", anon_calls=1, cache_hits=1,
            sql_total_time=2, sql_total_count=3, total_calls=1, total_time=4,
        ), model_to_dict(entries[0], exclude=["id"]))

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : HackAssistant
    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

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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_clast._meta.fields,
                    exclude=self.model_form_clast._meta.exclude
                )
            )
        form_set = self.ArrayFormSet(data, initial=form_set_initial, prefix=self.name)
        return form_set.has_changed()

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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_clast._meta.fields,
                            exclude=field.model_form_clast._meta.exclude
                        ))

        self.form_set = field.ArrayFormSet(data, initial=initial, prefix=self.html_name)

3 View Complete Implementation : test_api.py
Copyright MIT License
Author : openlegaldata
    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.astertEqual(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.astertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        self.astertTrue('label' in res.data, 'Error should be for `label` field')

3 View Complete Implementation : test_api.py
Copyright MIT License
Author : openlegaldata
    def test_write_as_guest(self):
        # Create
        res = self.client.post(reverse('annotationlabel-list'), data=model_to_dict(self.dummy_label), format='json')
        self.astertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

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

        # Delete
        res = self.client.delete(reverse('annotationlabel-detail', args=(2,)))
        self.astertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

3 View Complete Implementation : handlers.py
Copyright MIT License
Author : opennode
def preserve_fields_before_update(sender, instance, **kwargs):
    if instance.pk is None:
        return

    meta = instance._meta
    old_instance = meta.model._default_manager.get(pk=instance.pk)

    excluded_fields = [field.name for field in meta.many_to_many]
    excluded_fields.append(meta.pk.name)
    old_values = model_to_dict(old_instance, exclude=excluded_fields)

    setattr(instance, '_old_values', old_values)

0 View Complete Implementation : test_storage.py
Copyright MIT License
Author : catcombo
    def test_add_grouping(self):
        self.storage.add(
            view_name="app.view_name", method="GET", is_anon_call=True, is_cache_hit=False,
            sql_time=3, sql_count=2, view_execution_time=3,
        )
        self.storage.add(
            view_name="app.view_name", method="POST", is_anon_call=False, is_cache_hit=False,
            sql_time=10, sql_count=5, view_execution_time=7,
        )
        self.storage.add(
            view_name="app.view_name", method="GET", is_anon_call=True, is_cache_hit=True,
            sql_time=1, sql_count=1, view_execution_time=2,
        )

        entries = self.storage.fetch_all()
        dict_entries = [model_to_dict(e, exclude=["id"]) for e in entries]

        self.astertEqual(len(entries), 2)
        self.astertIn(dict(
            view_name="app.view_name", method="GET", anon_calls=2, cache_hits=1,
            sql_total_time=4, sql_total_count=3, total_calls=2, total_time=5,
        ), dict_entries)
        self.astertIn(dict(
            view_name="app.view_name", method="POST", anon_calls=0, cache_hits=0,
            sql_total_time=10, sql_total_count=5, total_calls=1, total_time=7,
        ), dict_entries)

0 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
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)

0 View Complete Implementation : encoder.py
Copyright MIT License
Author : Gerapy
    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)

0 View Complete Implementation : models.py
Copyright Mozilla Public License 2.0
Author : mozilla
    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_dict['delete_data'] = tri_to_quad(self.delete_data)

        # TODO: remove these two entries
        model_dict['numeric_reading_grade'] = self.numeric_reading_grade
        model_dict['reading_grade'] = self.reading_grade

        # 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

0 View Complete Implementation : test_api.py
Copyright MIT License
Author : openlegaldata
    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.astertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

0 View Complete Implementation : test_api.py
Copyright MIT License
Author : openlegaldata
    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.astertEqual(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.astertEqual(res.status_code, status.HTTP_200_OK)
        self.astertEqual(res.data['name'], updated_name)

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

        # Get to deleted item
        res = self.owner_client.get(reverse('annotationlabel-detail', args=(created_id,)))
        self.astertEqual(res.status_code, status.HTTP_404_NOT_FOUND)

0 View Complete Implementation : views.py
Copyright MIT License
Author : othreecodes
@login_required
def unread_messages(request):
    if not request.user.is_authenticated():
        data = {
            'unread_count':0,
            'unread_list':[]
        }
        return JsonResponse(data)

    unread_list = []
    messages = Message.objects.filter(recipient=request.user,read=False,deleted=False).order_by('date').reverse()
    for n in messages:
        struct = model_to_dict(n)
        if n.sender:
            struct['sender'] = str(n.sender)
        if n.recipient:
            struct['recipient'] = str(n.recipient)
        if n.date:
            struct['date'] = defaultfilters.timesince(n.date)
        if n.message:
            struct['message'] = str(n.message)
        struct['link'] = n.url()

        unread_list.append(struct)
    data = {
        'unread_count': messages.count(),
        'unread_list': unread_list
    }
    return JsonResponse(data)