<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mario Cerón Charry on Medium]]></title>
        <description><![CDATA[Stories by Mario Cerón Charry on Medium]]></description>
        <link>https://medium.com/@macercha?source=rss-250bdf836a3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VYbI7mdhJ9qykB5r1yrO3A@2x.jpeg</url>
            <title>Stories by Mario Cerón Charry on Medium</title>
            <link>https://medium.com/@macercha?source=rss-250bdf836a3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:46:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@macercha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Populating a “ChoiceField” and “TypedChoiceField” dynamically in Django Admin forms.]]></title>
            <link>https://macercha.medium.com/populating-a-choicefield-and-typedchoicefield-dynamically-in-django-admin-forms-4e7e6170c1ca?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e7e6170c1ca</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 11:17:51 GMT</pubDate>
            <atom:updated>2025-07-25T11:26:32.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETjzwSCojy4cmejeIsHtOw.jpeg" /><figcaption>Choose the right way.</figcaption></figure><p>Access a nested models in Django forms with a structured sort and remove the limits.</p><p>Django admin forms often require customized dropdowns to display model data in a specific order, such as by fields, properties, or methods like <em>__str__</em>. The <em>TypedChoiceField</em> offers a flexible solution for populating these dropdowns with sorted choices based on any model attribute. For example, in a nested Category model with a hierarchical <em>__str__</em> representation (e.g., “Books &gt; Fiction”), <em>TypedChoiceField</em> can be used to sort categories by their <em>__str__</em> output, enhancing the admin interface’s usability. This article explores how to leverage <em>TypedChoiceField</em> in Django admin forms to create sorted, user-friendly choice lists for various model features.</p><p>Go with the code. First, define the Category model:</p><pre>class Category(models.Model):<br>  name = models.CharField(max_length=150, null=False, blank=False, verbose_name=&quot;Name&quot;)<br>  parent = models.ForeignKey(&quot;self&quot;, null=True, blank=True, on_delete=models.CASCADE, verbose_name=&quot;Parent&quot;)<br><br>  def __str__(self) -&gt; str:<br>    &quot;&quot;&quot; Return a hierarchical string representation (e.g., &#39;Books &gt; Fiction&#39;) &quot;&quot;&quot;<br>    return (self.parent.__str() + &quot; &gt; &quot; if self.parent else &quot;&quot;) + self.name</pre><p>And add to the model some records like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fl4kGa%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fl4kGa%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fl4kGa%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c2773f340e831c56b710cf471335ba/href">https://medium.com/media/b5c2773f340e831c56b710cf471335ba/href</a></iframe><p>Now, create a simple ModelAdmin form.</p><pre>class CategoryAdminView(admin.ModelAdmin):<br>  list_display = [&quot;name&quot;, &quot;parent&quot;]<br>  list_per_page = 20</pre><p>Now, when you edit a category, you get a form with “name” and “parent” fields, and the “parent” field will be accessible through a <em>ModelChoiceField</em> control by default, but this control will be populated with the unsorted <em>queryset, o</em>f all records from the related model, if you use Category.objects.all(), or you can set a custom <em>queryset</em> to the control, to get an ordered list by some field. But, if you want to get an ordered list by representation? How to get an ordered list by <em>__str__</em> object representation? Simple… like all in Python/DJango.</p><p>Add and override “get_form” method and replace the <em>ModelChoiceField </em>control for a <em>TypedChoiceField</em> with a custom list elements getter method.</p><pre>class CategoryAdminView(admin.ModelAdmin):<br>  list_display = [&quot;name&quot;, &quot;parent&quot;]<br>  list_per_page = 20<br><br>  def _get_category_choices() --&gt; list:<br>    &quot;&quot;&quot; This method allow to get a sorted list using __str__ like a key &quot;&quot;&quot;<br>    # First, we validate if the app has been successfully loaded.<br>    app = apps.get_app_config(&quot;myapp&quot;)<br>   <br>    if app.is_ready:<br>      # Get the root categories<br>      qs = Category.objects.get_root_categories()<br>      # Create a sorted list using __str__ like a sort key.<br>      choices = [(x.id, x.__str__()) for x in sorted(qs.all(), key=lambda rcq: rcq.__str())]<br>    else:<br>      # Create empty list, if the app has not been loaded.<br>      choices = []<br>    # If you want to allow a None record.<br>    choices.insert(0, (0, None))<br>    return choices<br><br>  def get_form(self, request, obj: Category = None, **kwargs):<br>    &quot;&quot;&quot; Override get_form method &quot;&quot;&quot;<br>    # Get the base form<br>    form = super().get_form(request, obj, **kwargs)<br>    # Replace the base ChoiceField control with a TypedChoiceField populated with a sorted list<br>    form.base_fields[&quot;parent&quot;] = forms.TypedChoiceField(choices=self._get_category_choices(), coerce=int)<br>    return form</pre><p>The method used above, allow that you personalize the order of your choices using any feature of your model, including properties and methods. I hope you enjoy this code and your comments.</p><p><strong><em>The code is like this!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7e6170c1ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overriding “clean” method in ModelAdmin forms.]]></title>
            <link>https://macercha.medium.com/overriding-clean-method-in-modeladmin-forms-d501959d8b97?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d501959d8b97</guid>
            <category><![CDATA[django-forms]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-admin-clean-method]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 23:31:08 GMT</pubDate>
            <atom:updated>2025-03-06T23:31:08.956Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqT_hm0NLZtGOkTo" /><figcaption>Photo by <a href="https://unsplash.com/@davfts?utm_source=medium&amp;utm_medium=referral">David Pupăză</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The ModelAdmin object is a widely used class in Django, but the validations rely on the Model clean method, mainly because it creates its own instance of ModelForm class and its methods are not easily usable. But, sometimes, we need to access the methods of ModelForm class embedded in ModelAdmin object to perform our custom validations and send messages to admin form without closing it.</p><p>First, we need to understand that ModelAdmin create its own ModelForm embedded and to access it we need to use the “get_form” method.</p><pre>class BookAdmin(admin.ModelAdmin):<br>  list_display = (&quot;name&quot;, &quot;author&quot;)<br>  fields = &quot;__all__&quot;<br><br>  def get_form(self, request, obj, **kwargs):<br>    form = super().get_form(request, obj, **kwargs<br>    return form<br><br>  </pre><p>We now have control of the ModelForm object and use its methods and properties. Next, we need to override the clean method of the ModelForm object and replace with our custom method.</p><pre>class BookAdmin(admin.ModelAdmin):<br>  list_display = (&quot;name&quot;, &quot;author&quot;)<br>  fields = &quot;__all__&quot;<br><br>  def get_form(self, request, obj, **kwargs):<br>    def override_clean(target_form):<br>      # Write here your code to validate anything.<br>      return target_form.cleaned_data<br><br>    form = super().get_form(request, obj, **kwargs<br>    # Get the clean method.<br>    clean_method = getattr(form, &quot;clean&quot;, None)<br>    # If clean_method is callable, replace for our clean override method.<br>    if callable(clean_method):<br>      setattr(form, &quot;clean&quot;, override_clean)<br><br>    return form</pre><p>As you can see above, the steps are very simple, yet effective. Now, you can use the ModelForm clean method without losing the efficiency of the ModelAdmin class.</p><p><strong><em>Simple is better than complex.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d501959d8b97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement a PhoneField in Django]]></title>
            <link>https://macercha.medium.com/how-to-implement-a-phonefield-in-django-407d947df47b?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/407d947df47b</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 12:50:56 GMT</pubDate>
            <atom:updated>2024-04-05T12:50:56.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Public phones on the wall" src="https://cdn-images-1.medium.com/max/1024/0*GMl0hd_RyF_ej3xn" /><figcaption>Photo by <a href="https://unsplash.com/@eduardoequis?utm_source=medium&amp;utm_medium=referral">Eduardo Sánchez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Use of phone fields in personal data is very common, but how to store it with django ORM?. We commonly used one CharField and regular expression validators to ensure that the text complies with the format, but what if we added the dialing country code to our phone number? This is another history due to the many formats and lengths of this type of data.</p><p>To avoid this problem, it is very opular the use of two fields, one with dial country code to be dialed and another with the phone number, but with the implementation of JSONFields is possible to extend it in another field class and store it in a single field like an object.</p><p>First, define a new extended class of JSONField and override the “<em>__init__”</em> method to send to constructor the default “<em>dial_code</em>” to use and an optional “dial_codes” argument containing a TextChoices class enumerator to validate the dial country codes allowed.</p><pre>class PhoneField(JSONField):<br>    description = _(&quot;A Phone Field object&quot;)<br><br>    def __init__(self, encoder=None, decoder=None, dial_code: str = &quot;+57&quot;, *args, **kwargs):<br>        self.dial_code = dial_code<br>        self.phone_number = 0<br>        self.dial_codes = kwargs.get(&quot;dial_codes&quot;, None)<br>        super().__init__(encoder=encoder, decoder=decoder, *args, **kwargs)</pre><p>Now, override two methods “<em>from_db_value</em>” and “<em>validate</em>” to get the data and validate the right keys within the json structure.</p><pre>def from_db_value(self, value, expression, connection):<br>    value = super().from_db_value(value, expression, connection)<br>    if value is not None:<br>        self.phone_number = value.get(&quot;phone_number&quot;)<br>        self.dial_code = value.get(&quot;dial_code&quot;)<br>    return value<br><br>def validate(self, value, model_instance):<br>    super().validate(value, model_instance)<br>    if &quot;dial_code&quot; not in value:<br>        value[&quot;dial_code&quot;] = self.dial_code<br>    if not {&quot;dial_code&quot;, &quot;phone_number&quot;} &lt;= value.keys():<br>        raise ValidationError(_(&quot;&#39;dial_code&#39; and &#39;phone_number&#39; keys are required.&quot;))<br>    if len(value) &gt; 2:<br>        raise ValidationError(_(&quot;Number of keys major than required. Please try again.&quot;))<br>    if not isinstance(value.get(&quot;phone_number&quot;), int) or not isinstance(value.get(&quot;dial_code&quot;), str):<br>        raise ValidationError(_(&quot;Type of field keys are wrong. Please try again.&quot;))<br>    if self.dial_codes:<br>        if not value.get(&quot;dial_code&quot;) in self.dial_codes.dial_codes_list():<br>            raise ValidationError(_(&quot;Country code is not valid. Please try again.&quot;))</pre><p>Lastly, create “<em>__str__”</em> method to get the string field representation if you need it.</p><pre>def __str__(self):<br>    return f&quot;{self.dial_code} + &#39; &#39; + {str(self.phone_number)}&quot;</pre><p><em>The code is like this!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407d947df47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serializando un “ImageField” con Django Rest Framework.]]></title>
            <link>https://macercha.medium.com/serializando-un-imagefield-con-django-rest-framework-e476d30f4e7f?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e476d30f4e7f</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 15:20:52 GMT</pubDate>
            <atom:updated>2023-08-20T15:20:52.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGlT_z4GUpsvvVLDF0HsrQ.jpeg" /><figcaption>Django Programming Kit</figcaption></figure><p>El manejo de imágenes en django es un desafío por sí mismo, pero si se requiere incorporar este tipo de campos en servicios REST, es un poco más complejo. Exploremos como podemos lograr utilizar el poder de DRF para incorporar de manera práctica la posibilidad de cargar, actualizar, eliminar y obtener imágenes almacenadas a través de campos del tipo “<em>ImageField</em>”.</p><p>En primera instancia, podemos apoyarnos en la librería <a href="https://github.com/Hipo/drf-extra-fields">drf-extra-fields</a> lo que nos permitirá incorporar algunos tipos de campos especiales que nos faciliten el trabajo. Si bien podemos utilizar directamente la clase <em>Base64ImageField</em>, que permite encapsular un <em>ImageField</em> codificado en base64, en nuestro caso particular utilizaremos <em>HybridImageField</em> para obtener la flexibilidad que se requiere en este caso.</p><pre>from rest_framework import serializers<br>from drf_extra_fields.fields import HybridImageField<br><br>class ProfileSerializer(serializers.ModelSerializer):<br>  pic_file = HybridImageField(max_length=None, required=False, allow_null=True, represent_in_base64=True)<br><br>  class Meta:<br>    model = MyModel<br>    fields = (&quot;username&quot;, &quot;pic_file&quot;)<br></pre><p>El anterior fragmento de código utiliza la clase <em>HybridImageField</em> y adicionalmente pasa el parámetro “<em>represent_in_base64</em>” en True para que el serializador retorne el campo <em>ImageField</em> en formato <strong>base64</strong>, sin embargo, esta clase de campo permite que sea manejable desde un form en Django sin que tengamos que realizar alguna modificación, es decir, un <em>ImageField</em> normal.</p><p>Ahora, para potenciar un poco nuestro serializador, podemos crear una clase propia <em>HybridImageField</em> que herede de la clase base de la librería y otorgarle la capacidad de validar el ancho y alto de la imágen para controlar el tamaño que recibimos de esta.</p><pre>from django.core.exceptions import ValidationError<br>from django.utils.translation import gettext_lazy as _<br>from drf_extra_fields.fields import HybridImageField as SourceHybridImageField<br>from drf_extra_fields.fields import Base64FieldMixin, ImageField<br>from typing import Any<br><br>class HybridImageField(SourceHybridImageField):<br>    &quot;&quot;&quot;<br>    Inherited class from drf_extra_fields.field.HybridImageField to allow size validation and implement the use image<br>    format and size validation<br>    &quot;&quot;&quot;<br>    INVALID_FILE_SIZE = _(&quot;The width or height of the file is invalid.&quot;)<br>    def __init__(self, *args: Any, **kwargs: Any) -&gt; None:<br>        &quot;&quot;&quot;<br>        HybridImageField class constructor<br><br>        Parameters<br>        ----------<br>        *args: Tuple with parameters values<br>        **kwargs: Parameter dictionary with key/values<br>        &quot;&quot;&quot;<br>        self.max_image_width = kwargs.pop(&quot;image_width&quot;, 0)<br>        self.max_image_height = kwargs.pop(&quot;image_height&quot;, 0)<br>        super().__init__(*args, **kwargs)<br><br>    def to_internal_value(self, data):<br>        &quot;&quot;&quot;<br>        Override method to process internal data from serializer<br><br>        Parameters<br>        ----------<br>        data: Data received from serializer (raw post data)<br><br>        Returns<br>        -------<br>        Python data compatible<br>        &quot;&quot;&quot;<br><br>        if self.represent_in_base64:<br>            if self.max_image_width &gt; 0 and self.max_image_height &gt; 0:<br>                width, height = self.__get_file_size(data)<br>                if width &gt; self.max_image_width or height &gt; self.max_image_height:<br>                    raise ValidationError(self.INVALID_FILE_SIZE)<br>            image_field = Base64FieldMixin.to_internal_value(self, data)<br>        else:<br>            image_field = ImageField.to_internal_value(self, data)<br>        return image_field<br><br>    def __get_file_size(self, data: str) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Get the file size from base64 encoded bytes<br><br>        Parameters<br>        ----------<br>        base64_data: Base64 encoded bytes<br><br>        Returns<br>        -------<br>        width, height: Tuple with width and height values<br>        &quot;&quot;&quot;<br>        try:<br>            from PIL import Image<br>            base64_data = base64.b64decode(data)<br>            image = Image.open(io.BytesIO(base64_data))<br>        except (ImportError, OSError):<br>            raise ValidationError(self.INVALID_FILE_MESSAGE)<br>        else:<br>            width, height = image.size<br>        return width, height</pre><p>En esta definición de clase implementamos tres cambios básicos:</p><ol><li>Obtenemos de los parámetros del método constructor los valores <em>image_width</em> e <em>image_height</em> para tener la base con los que validaremos el ancho y alto de la imagen.</li><li>Sobreescribimos el método <em>to_internal_value</em> para que en este realicemos el proceso de validación del tamaño de la imagen y lanzar una excepción si esta no cumple.</li><li>Definimos un método privado para obtener el tamaño, utilizando la clase <em>Image</em> de la librería <a href="https://pypi.org/project/Pillow/"><strong><em>Pillow</em></strong></a>, y retornar la tupla con los valores al método <em>to_internal_value</em>.</li></ol><p>Estas simples modificaciones nos permiten potenciar la clase de la librería y realizar validaciones mucho más profundas a las imágenes enviadas a través de los <em>ViewSets</em> de <strong><em>rest_framework</em></strong>.</p><p><em>El código así es!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e476d30f4e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[El poder de los “tags” en los templates de Django.]]></title>
            <link>https://macercha.medium.com/el-poder-de-los-tags-en-los-templates-de-django-ff8e212dbacc?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8e212dbacc</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-taggit]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[django-template]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 13:02:06 GMT</pubDate>
            <atom:updated>2023-08-10T13:02:06.150Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gXBENn-DTWrxOkVQhlNmg.jpeg" /><figcaption>Río Magdalena — Pericongo — Colombia</figcaption></figure><p>Una de las mejores y más sorprendentes características que nos ofrecen los templates de django es el uso de los “tags”. Estos pueden ser utilizados casi para cualquier cosa.</p><p>Django incluye algunos para usos genéricos, como por ejemplo, realizar ciclos for, definir ciclos de clases, comentar el código en el template, entre muchos otros. Sin embargo, en muchas ocasiones necesitamos operar cadenas de caracteres, realizar totales dentro de listas de diccionarios e incluso generar un sub total sobre varias claves, basados en una clave específica… pues bien… los “tags” también nos pueden ayudar.</p><p>A continuación les doy algunos ejemplos que se pueden utilizar para este tipo de tareas.</p><h4>Concatenar cadenas.</h4><p>Si necesita utilizar una concatenación de cadenas que haga en tiempo de ejecución (render) del template de manera similar a lo que hace el operador “%”, podemos definir un tag que nos ayude a hacerlo.</p><pre>from django import template<br><br>register = template.Library()<br><br><br>@register.simple_tag<br>def string_concat(first_string: str, *args):<br>    &quot;&quot;&quot;<br>    Simple tag to concatenate one string with strings tuple.<br><br>    Parameters<br>    ----------<br>    first_string : Base string to concatenate<br>    args : Strings tuple<br><br>    Returns<br>    -------<br>    Concatenated string<br>    &quot;&quot;&quot;<br>    return first_string % args</pre><p>Se puede utilizar en casos en los que se quiere tener un texto completo que podamos justificar y utilizar dentro de un párrafo o bloque, a partir de la concatenación de varios textos, por ejemplo:</p><pre>var1 = &quot;Certificamos que %s ha desarrollado exitosamente el proyecto %s en lenguaje %s&quot;<br>print(var1 % (&quot;Pepito Pérez&quot;, &quot;Template Tags&quot;, &quot;Python&quot;))</pre><p>Lo podrían hacer así en el template:</p><pre>{% load string_concat %}<br>{% block detail %}<br>    &lt;div class=&quot;text-large text-justify&quot;&gt;<br>        {% string_concat &quot;Certificamos que %s ha desarrollado exitosamente el proyecto %s en lenguaje %s&quot; user_name project_name lang_name as content_body %}<br>        {{ content_body|safe }}<br>    &lt;/div&gt;<br>{% endblock %}</pre><h4>Totalizar una lista de registros (dictionary).</h4><p>Otro buen ejemplo, es implementar un tag que calcule el total de un campo partícular sobre una lista de registros basada en diccionarios. El código del tag sería así:</p><pre>from django import template<br><br><br>register = template.Library()<br><br><br>@register.simple_tag<br>def sum_dict(source_list: list, key: str, format_string: str = None):<br>    &quot;&quot;&quot;<br>    Template tag to get a sum from a list of dictionary records.<br><br>    Parameters<br>    ----------<br>    source_list : List with dict records.<br>    key : Key string name to make the sum.<br>    format_string : Format to be used at render template.<br><br>    Returns<br>    -------<br>    f_sum: String with formatted result of sum operation.<br>    &quot;&quot;&quot;<br>    sum_result = 0<br>    if isinstance(source_list, list):<br>        if len(source_list) &gt; 0 and isinstance(source_list[0], dict):<br>            if key in source_list[0].keys():<br>                for record in source_list:<br>                    if record.get(key) is not None and (type(record.get(key)) == int or float):<br>                        sum_result += record.get(key)<br><br>    if format_string is not None:<br>        format_string = &quot;{0:&quot; + format_string + &quot;}&quot;<br>        f_sum = format_string.format(sum_result)<br>    else:<br>        f_sum = f&quot;{sum_result}&quot;<br>    return f_sum</pre><p>Ahora, suponga que tiene un listado de registros “total_paises” cuyos campos son: nombre_pais, hombres, mujeres; y queremos generar una tabla con los totales.</p><pre>{% load sum_dict %}<br>&lt;table&gt;<br>  {% for record in total_paises %}<br>    &lt;tr&gt;<br>      &lt;td&gt;<br>        {{record.nombre_pais}}<br>      &lt;/td&gt;<br>      &lt;td&gt;<br>        {{record.hombres}}<br>      &lt;/td&gt;<br>      &lt;td&gt;<br>        {{record.mujeres}}<br>      &lt;/td&gt;<br>    &lt;/tr&gt;<br>  {% endfor %}<br>  &lt;tr&gt;<br>    &lt;td&gt;<br>      Totales<br>    &lt;/td&gt;<br>    &lt;td&gt;<br>      {% sum_dict total_paises &quot;hombres&quot; &quot;,.0f&quot; %}<br>    &lt;/td&gt;<br>    &lt;td&gt;<br>      {% sum_dict total_paises &quot;mujeres&quot; &quot;,.0f&quot; %}<br>    &lt;/td&gt;<br>  &lt;/tr&gt;<br>&lt;/table&gt;</pre><p>Este tag nos permite generar en el proceso de “render” del template los totales sin tener que calcularlos previamente, cosa que es muy útil en muchas ocasiones, incluso cuando se utilizan los “templates” para la generación de documentos “pdf” u otro formato.</p><p>Es posible, entonces, expandir aún más el poderío que nos entregan los “tags” al utilizarlos en las diferentes aplicaciones que tienen los “templates” de django.</p><p><em>El código así es!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8e212dbacc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Permisos Django Rest Framework y “rest-framework-simplejwt”]]></title>
            <link>https://macercha.medium.com/permisos-django-rest-framework-y-rest-framework-simplejwt-921ed648447d?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/921ed648447d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[simple-jwt]]></category>
            <category><![CDATA[decorators]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 13:25:36 GMT</pubDate>
            <atom:updated>2022-08-10T13:25:36.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Permisos en Django Rest Framework y “rest-framework-simplejwt”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmDanvlsdrlv3l7VHV1Q3g.jpeg" /></figure><p>Muchos de nosotros hemos utilizado los decoradores de django para controlar los accesos a los diferentes servicios REST que exponemos utilizando el sistema de autenticación que nos provee el mismo django. Sin embargo, al implementar autenticación basada en la librería “rest-framework-simplejwt” se presenten errores debido a que esta librería retorna un objeto de tipo “TokenUser” y no un objeto “User”, que es el que requieren los decoradores.</p><p>Para esto, necesitamos simplemente reescribir nuestro decorador “permisión_required” para que haga la conversión desde la clase “TokenUser” a nuestra, ya conocida, clase “User” para luego utilizarlo en nuestro código de servicios REST.</p><p>A continuación podemos ver un ejemplo sencillo de la manera en la que se podría implementar nuestro nuevo código para reemplazar el antiguo “permission_required” nativo de django. En el se observa, como a partir del objeto “TokenUser” se obtiene el objeto “User” que requerimos para hacer las validaciones.</p><pre>from django.contrib.auth.decorators import user_passes_test<br>from django.contrib.auth.models import User<br>from django.core.exceptions import PermissionDenied<br>from rest_framework_simplejwt.models import TokenUser</pre><pre>def permission_required(perm, raise_exception=True):<br>    <em>&quot;&quot;&quot;<br>    Override default permission required decorator<br>    </em><strong><em>:param</em></strong><em> perm: permissions tuple or str<br>    </em><strong><em>:param</em></strong><em> raise_exception: True if you want to raise PermissionDenied exception<br>    </em><strong><em>:return</em></strong><em>: True if success, otherwise False<br>    &quot;&quot;&quot;<br>    </em>def check_perms(user):<br>        b_return = False<br>        local_user = user<br>        # If user is from rest_framework<br>        if isinstance(user, TokenUser):<br>            local_user = User.objects.get(pk=user.id)</pre><pre>if isinstance(perm, str):<br>            perms = (perm,)<br>        else:<br>            perms = perm</pre><pre>if local_user.has_perm(perms) or local_user.is_superuser:<br>            b_return = True<br>        elif raise_exception:<br>            raise PermissionDenied<br>        return b_return<br>    return user_passes_test(check_perms)</pre><p>Y ahora, veamos la forma en la que podemos implementarlo fácilmente en un método de un ModelViewSet. En este pequeño fragmento de código podemos observar en negrita la implementación de nuestro decorador y validar así los permisos que requerimos, que puede ser uno solo o una tupla de cadenas de caracteres que contienen los diferentes permisos requeridos.</p><pre>from django.utils.decorators import method_decorator<br><strong>from own_decorators.rest_framework import permission_required</strong><br>from rest_framework.request import Request<br>from rest_framework.response import Response<br>from rest_framework.viewsets import ModelViewSet<br>from serializers import MySerializer<br>from models import Trigger<br>from typing import Any</pre><pre>class MyService(ModelViewSet):<br><em>    </em>queryset = MyModel.objects.all()<br>    serializer_class = MySerializer</pre><pre><strong>@method_decorator(permission_required(&quot;mymodel.view_mymodel&quot;))</strong><br>    def list(self, request: Request, *args: Any, **kwargs: Any):<br>        pass</pre><p>El código así es!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=921ed648447d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sobrecargando métodos y/o funciones en Angular]]></title>
            <link>https://macercha.medium.com/sobrecargando-m%C3%A9todos-en-angular-3dbdffba176b?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dbdffba176b</guid>
            <category><![CDATA[overload]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[sobrecarga]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 11:08:36 GMT</pubDate>
            <atom:updated>2021-11-05T11:10:03.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ns-lknW1ZqTgG4EgaFXt7Q.jpeg" /><figcaption>Café de Colombia</figcaption></figure><p>Muchas veces requerimos utilizar un mismo método con diferentes parámetros en Angular y, si bien podemos utilizar la validación de las variables, existen buenas prácticas que debemos usar para que nuestros sistemas validen su correcto uso.</p><p>A continuación les dejo un pequeño ejemplo de como lo he venido haciendo obteniendo muy buenos resultados en la validación de su utilización y en la generación de la documentación, algo que al final resulta ser muy útil.</p><pre>class Book {};</pre><pre>// Sobrecarga 1<br>function getBook(id: number): Book;</pre><pre>// Sobrecarga 2<br>function getBook(author: string, title: string): Book;</pre><pre>// Definición de la función a sobrecargar<br>function getBook(param1: number | string, title?: string): Book {<br>  if (typeof param1 === &#39;number&#39;) {<br>    // Carga el libro por ID<br>  } else {<br>    // Carga el libro por autor y titulo<br>  }<br>  return Book;<br>}</pre><p>El anterior fragmento de código solo ofrece dos posible formas de sobrecarga de la función, evitando así la mala utilización en cualquiera de los sitios donde la requiramos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dbdffba176b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[¿Cómo simular la sobrecarga de métodos o constructores en Python?]]></title>
            <link>https://macercha.medium.com/c%C3%B3mo-simular-la-sobrecarga-de-m%C3%A9todos-o-constructores-en-python-757169d7aa2?source=rss-250bdf836a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/757169d7aa2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[sobrecarga]]></category>
            <dc:creator><![CDATA[Mario Cerón Charry]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 17:22:35 GMT</pubDate>
            <atom:updated>2021-08-09T17:22:35.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKfuDYjeZi7Og16Z-nlikw.jpeg" /></figure><p>Muchas veces hemos utilizado métodos sobrecargados en lenguajes como Java, JavaScript o C#, entre otros, y hemos podido disfrutar de las posibilidades que este tipo de métodos nos ofrecen ya sea para la ejecución de una tarea sobre un objeto o la posible instanciación de una clase a partir de diferentes variables. Pues bien, Python no ofrece esta posibilidad de manera directa, pero con un poco de ingenio y código podemos realizar una simulación que nos permita de cierta forma lograr nuestro objetivo.</p><p>Una de las formas de lograr lo anterior es la validación de parámetros durante el proceso de ejecución del método o la instanciación de la clase, tal como observamos en el siguiente fragmento de código.</p><pre>class MyClass:<br>    def __init__(self, a: int = None, b: str = None):<br>        if a:<br>            self.__filename = &quot;result_&quot; + str(a) + &quot;.txt&quot;<br>        else:<br>            if b:<br>                self.__filename = b<br>            else:<br>                TypeError(&quot;Se requiere al menos un argumento!&quot;)<br>                <br>    def get_filename(self):<br>        return self.__filename</pre><p>De manera similar se puede aplicar para cualquier método o función que queramos definir dentro de nuestros proyectos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757169d7aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>