<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: sevdimali</title>
    <description>The latest articles on Forem by sevdimali (@sevdimali).</description>
    <link>https://forem.com/sevdimali</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F12993%2F7975087.png</url>
      <title>Forem: sevdimali</title>
      <link>https://forem.com/sevdimali</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sevdimali"/>
    <language>en</language>
    <item>
      <title>Custom Django Admin Actions</title>
      <dc:creator>sevdimali</dc:creator>
      <pubDate>Thu, 19 Jan 2023 13:58:54 +0000</pubDate>
      <link>https://forem.com/sevdimali/custom-django-admin-actions-3m84</link>
      <guid>https://forem.com/sevdimali/custom-django-admin-actions-3m84</guid>
      <description>&lt;p&gt;Django Admin Actions allows us to make bulk operations. The default one is the delete action.&lt;/p&gt;

&lt;p&gt;Django allows us to create our custom actions.&lt;/p&gt;

&lt;p&gt;For example, let’s think of a situation where we have a company model, and we regularly export data based on company types.&lt;/p&gt;

&lt;p&gt;For this case, we will create our custom action and we will be able to export selected types of companies.&lt;/p&gt;

&lt;p&gt;Let's start :)&lt;/p&gt;

&lt;p&gt;As a first step, we will create our model and register it in admin.py:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;models.py&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.db import models

OPTIONS = (
    ('telco', 'Telecommunication'),
    ('log', 'Logistics'),
    ('agr', 'Agriculture'),
    ('aero', 'Aerospace'),
    ('pharm', 'Pharmaceutical'),
)


class Company(models.Model):
    name = models.CharField(max_length=255)
    company_type = models.CharField(max_length=15, choices=OPTIONS)
    founded = models.DateField(null=True, blank=True)
    status = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Company'
        verbose_name_plural = 'Companies'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;admin.py&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin

from core.models import Company


class CompanyAdmin(admin.ModelAdmin):

    list_display = ['name', 'company_type', 'founded', 'status']

    list_filter = ['company_type']


admin.site.register(Company, CompanyAdmin)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's add some data to our database:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsubkc3a4mczhzb5ikds.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvsubkc3a4mczhzb5ikds.png" alt="Image description" width="800" height="263"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will modify our admin.py as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin
from django.http import HttpResponseRedirect

from core.models import Company


class CompanyAdmin(admin.ModelAdmin):

    @admin.action(description='Export')
    def export_objects(self, request, queryset):
        selected = queryset.values_list('pk', flat=True)
        return HttpResponseRedirect('/export/?ids=%s' % (
            ','.join(str(pk) for pk in selected),
        ))

    list_display = ['name', 'company_type', 'founded', 'status']

    actions = [export_objects]

    list_filter = ['company_type']


admin.site.register(Company, CompanyAdmin)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we created our action function(export_objects), here we get selected object’s ids from the queryset and passed them as a get parameter to our export URL.&lt;/p&gt;

&lt;p&gt;Also in our CompanyAdmin class, we added a new action to actions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;actions = [export_objects]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So in this step, we have to create our export view and URL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;urls.py&lt;/strong&gt;&lt;br&gt;
from django.contrib import admin&lt;br&gt;
from django.urls import path&lt;br&gt;
from core.views import export&lt;/p&gt;

&lt;p&gt;urlpatterns = [&lt;br&gt;
    path('admin/', admin.site.urls),&lt;br&gt;
    path('export/', export, name='export'),&lt;br&gt;
]&lt;br&gt;
&lt;strong&gt;views.py&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.core import serializers
from django.http import HttpResponse
from core.models import Company


def export(request):
    ids = request.GET.get('ids').split(',')
    qs = Company.objects.filter(id__in = ids)
    response = HttpResponse(content_type="application/json")
    serializers.serialize("json", qs, stream=response)
    return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final result is like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faq3awt3rpi5tu92lt6kz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faq3awt3rpi5tu92lt6kz.png" alt="Image description" width="800" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The complete source code is available &lt;a href="https://github.com/sevdimali/admin-custom-action" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for reading. I hope you enjoyed it ❤.&lt;br&gt;
The post first appeared in my blog&lt;br&gt;
Keep Learning..!&lt;/p&gt;

</description>
      <category>programming</category>
      <category>webdev</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>How to create thumbnails programmatically in Django</title>
      <dc:creator>sevdimali</dc:creator>
      <pubDate>Mon, 16 Jan 2023 16:28:02 +0000</pubDate>
      <link>https://forem.com/sevdimali/how-to-create-thumbnails-programmatically-in-django-1058</link>
      <guid>https://forem.com/sevdimali/how-to-create-thumbnails-programmatically-in-django-1058</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1pxwjgi05h3nhgc9ksn7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1pxwjgi05h3nhgc9ksn7.png" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Django-imagekit is an app for processing images. You can programmatically change images with imagekit. For this blog post, we will create thumbnails and look for its Django Rest Framework usage (DRF).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Installation of django-imagekit&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pillow
pip install django-imagekit
INSTALLED_APPS = [
'imagekit',
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Creating a thumbnail with django-imagekit&lt;/strong&gt;&lt;br&gt;
For creating a thumbnail in Django from an image we will use ImageSpecField. An image spec is a type of image generator that generates a new image from a source image. Now let’s look for a specific example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Models.py&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    picture = models.ImageField(null=True, upload_to="images/", blank=True, verbose_name="Category picture")
    thumbnail150x150 = ImageSpecField(source='picture', processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we specified source=’picture’, in this way we tell use the picture field as a source and generate a new image.&lt;/p&gt;

&lt;p&gt;So in your templates, you can simply use it like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;img src="{{ category.thumbnail150x150.url }}" alt="img"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to not create a new image, just change the original image, then we will use ProcessedImageField and replace a source to upload_to.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    thumbnail150x150 = ProcessedImageField(upload_to="images/", processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are able to use as many processors as you’d like, which will all be run in order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    picture = models.ImageField(null=True, upload_to="images/", blank=True, verbose_name="Category picture")
    thumbnail150x150 = ImageSpecField(source='picture', processors=[ResizeToFill(150, 150), TrimBorderColor(), ],
                                      format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. “django-imagekit” usage with DRF(Django Rest Framework)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CategorySerializer(serializers.ModelSerializer):
    picture = serializers.SerializerMethodField()
    thumbnail = serializers.SerializerMethodField()
    class Meta:
        model = Category
        fields = ('id', 'name', 'picture','thumbnail')
    def get_picture(self, obj):
        return obj.picture.url
    def get_thumbnail(self, obj):
        return obj.thumbnail150x150.url
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Thanks for reading. I hope you enjoyed it ❤.&lt;br&gt;
The post first appeared in &lt;a href="https://medium.com/@sevdimali" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;&lt;br&gt;
Keep Learning..!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>learning</category>
      <category>tutorial</category>
      <category>education</category>
    </item>
    <item>
      <title>How to use UUID in Django</title>
      <dc:creator>sevdimali</dc:creator>
      <pubDate>Sat, 03 Dec 2022 11:27:30 +0000</pubDate>
      <link>https://forem.com/sevdimali/how-to-use-uuid-in-django-32gk</link>
      <guid>https://forem.com/sevdimali/how-to-use-uuid-in-django-32gk</guid>
      <description>&lt;p&gt;UUID(Universal Unique Identifier) is a Python library that generates random objects of 128 bits. It is a standard built-in Python library which means you don’t need to install anything. There are three main algorithms used for generating randoms:&lt;/p&gt;

&lt;p&gt;Using IEEE 802 MAC addresses as a source of uniqueness&lt;br&gt;
Using pseudo-random numbers&lt;br&gt;
Using well-known strings combined with cryptographic hashing&lt;br&gt;
The UUID uses getnode() to retrieve the MAC value on a given system:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import uuid
print(uuid.getnode())
251053329979042
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, let’s look at how we can use UUID in general:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import uuidp
print(uuid.uuid4())
cae6f5a3-377d-4eaa-8d27-3ff12aece93e
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;UUID usage in Django&lt;br&gt;
Now, let’s look at using UUID usage in Django.&lt;/p&gt;

&lt;p&gt;It is commonly used to replace the Django id field. By default, Django gives each model auto-incrementing primary key field:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;id = models.AutoField(primary_key=True)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;if you want to explicitly set the primary key you must specify primary_key=True then Django won’t add this field automatically because it detects that you set it manually.&lt;/p&gt;

&lt;p&gt;Now let’s look real example. Assume that you have a Subscription Model&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Subscription (models.Model):
name = models.CharField(verbose_name=_("Subcription Name"),
                        help_text=_("Required and unique"),
                        max_length=255,
                        unique=True,
)
cdate = models.DateTimeField(auto_now_add=True)
udate = models.DateTimeField(auto_now=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In general when we access this model’s detail like below:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;https://domain.com/subcriptions/1&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the frontend, users can access other’s data by replacing 1 to 2,3,4, etc. We can call it a simple Security leak. For in these cases we can replace the id field with UUID.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Subscription (models.Model):
id = models.UUIDField(primary_key=True,
                      default=uuid.uuid4,
                      editable=False)
                      name = models.CharField(
                      verbose_name=_("Subcription Name"),
                      help_text=_("Required and unique"),
                      max_length=255,
                      unique=True,
                      )
cdate = models.DateTimeField(auto_now_add=True)
udate = models.DateTimeField(auto_now=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we showed above UUID generates random and it is not predictable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for reading. I hope you enjoyed it ❤.&lt;br&gt;
The post first appeared in &lt;a href="https://sevdimali.medium.com/" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;&lt;br&gt;
Keep Learning..!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>Creating thumbnails programmatically in Django using django-imagekit</title>
      <dc:creator>sevdimali</dc:creator>
      <pubDate>Tue, 29 Nov 2022 16:35:06 +0000</pubDate>
      <link>https://forem.com/sevdimali/creating-thumbnails-programmatically-in-django-using-django-imagekit-2l1e</link>
      <guid>https://forem.com/sevdimali/creating-thumbnails-programmatically-in-django-using-django-imagekit-2l1e</guid>
      <description>&lt;p&gt;Django-imagekit is an app for processing images. You can programmatically change images with imagekit. For this blog post, we will create thumbnails and look for its Django Rest Framework usage (DRF).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Installation of django-imagekit&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pillow
pip install django-imagekit
INSTALLED_APPS = [
'imagekit',
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Creating a thumbnail with django-imagekit&lt;/strong&gt;&lt;br&gt;
For creating a thumbnail in Django from an image we will use ImageSpecField. An image spec is a type of image generator that generates a new image from a source image. Now let’s look for a specific example.&lt;/p&gt;

&lt;p&gt;Models.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    picture = models.ImageField(null=True, upload_to="images/", blank=True, verbose_name="Category picture")
    thumbnail150x150 = ImageSpecField(source='picture', processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we specified source=’picture’, in this way we tell use the picture field as a source and generate a new image.&lt;/p&gt;

&lt;p&gt;So in your templates, you can simply use it like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;img src="{{ category.thumbnail150x150.url }}" alt="img"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to not create a new image, just change the original image, then we will use ProcessedImageField and replace a source to upload_to.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    thumbnail150x150 = ProcessedImageField(upload_to="images/", processors=[ResizeToFill(150, 150)], format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are able to use as many processors as you’d like, which will all be run in order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Category(models.Model):
    name = models.CharField(
        verbose_name=_("Category Name"),
        help_text=_("Required and unique"),
        max_length=255,
        unique=True,
    )
    picture = models.ImageField(null=True, upload_to="images/", blank=True, verbose_name="Category picture")
    thumbnail150x150 = ImageSpecField(source='picture', processors=[ResizeToFill(150, 150), TrimBorderColor(), ],
                                      format="PNG",
                                      options={'quality': 60})
    cdate = models.DateTimeField(auto_now_add=True)
    udate = models.DateTimeField(auto_now=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;“django-imagekit” usage with DRF(Django Rest Framework)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CategorySerializer(serializers.ModelSerializer):
    picture = serializers.SerializerMethodField()
    thumbnail = serializers.SerializerMethodField()
    class Meta:
        model = Category
        fields = ('id', 'name', 'picture','thumbnail')
    def get_picture(self, obj):
        return obj.picture.url
    def get_thumbnail(self, obj):
        return obj.thumbnail150x150.url
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks for reading. I hope you enjoyed it ❤.&lt;br&gt;
The post first appeared in &lt;a href="https://medium.com/@sevdimali" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Keep Learning..!&lt;/p&gt;

</description>
      <category>css</category>
      <category>design</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
