<?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 Borhan Tipu on Medium]]></title>
        <description><![CDATA[Stories by Borhan Tipu on Medium]]></description>
        <link>https://medium.com/@imtipu?source=rss-fe182178a316------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IcTmS-OSYdzEY2mNq0CbiA.jpeg</url>
            <title>Stories by Borhan Tipu on Medium</title>
            <link>https://medium.com/@imtipu?source=rss-fe182178a316------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imtipu/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[Use Firebase Storage as Django Default File Storage]]></title>
            <link>https://imtipu.medium.com/firebase-storage-as-django-default-file-storage-613a9451a6a4?source=rss-fe182178a316------2</link>
            <guid isPermaLink="false">https://medium.com/p/613a9451a6a4</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[django-storages]]></category>
            <category><![CDATA[firebase-storage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Borhan Tipu]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 06:48:28 GMT</pubDate>
            <atom:updated>2025-12-21T12:01:09.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KI1JoZ2QQ_QMGMLx1Zl_Q.png" /><figcaption>Firebase Storage with Django</figcaption></figure><p>This guide walks you through integrating Firebase Storage with a Django project using the Firebase Admin SDK. It follows the exact configuration used in this codebase, so you can copy–paste safely.</p><h3>What You’ll Build</h3><ul><li>A custom Django storage backend powered by Firebase Storage.</li><li>Environment-based toggle to switch between local file storage and Firebase Storage.</li><li>Signed URLs and public URLs for serving files securely.</li></ul><h3>Why Firebase Storage?</h3><ul><li>Global delivery via Google’s infrastructure with low‑ops overhead.</li><li>Simple Python SDK for uploads, signed URLs, and metadata.</li><li>Flexible security using service accounts and IAM.</li><li>Great for media (images, documents, avatars) with CDN‑friendly URLs.</li></ul><p>Alternatives to consider: Amazon S3, Cloudflare R2, Supabase Storage, or the local filesystem for development. You can use <a href="https://pypi.org/project/django-storages/">django-storages</a> for ther storage services.</p><h3>Prerequisites</h3><p><strong>You can try other python and django versions.</strong></p><ul><li>Python 3.12+</li><li>Django 5.2+</li><li>A Firebase project with a Storage bucket</li><li>Service Account credentials for your Firebase project</li></ul><p>Dependencies are already managed via pyproject.toml (includes firebase-admin and django-environ). If you prefer pip, see the commands below.</p><h3>1) Install Dependencies</h3><ul><li>Using pip</li></ul><pre>pip install firebase-admin django-environ</pre><ul><li>Using uv</li></ul><pre>uv add firebase-admin django-environ</pre><h3>2) Prepare Firebase Service Account</h3><ol><li>Go to Google Cloud Console → IAM &amp; Admin → Service Accounts → Create key.</li><li>Choose JSON and download the file.</li><li>You’ll copy values from this JSON into environment variables (see below).</li></ol><p>Important fields (names match your settings.py):</p><ul><li>project_id</li><li>private_key_id</li><li>private_key (keep secure, replace literal newlines with \n in .env)</li><li>client_email</li><li>client_id</li><li>Your Firebase Storage bucket name (e.g., my-project.appspot.com)</li></ul><h3>3) Configure Environment Variables (.env)</h3><p>Create or update your .env file at the project root:</p><pre>USE_FIREBASE_STORAGE=True<br>FIREBASE_STORAGE_BUCKET=&lt;bucket_name&gt;<br>FIREBASE_PROJECT_ID=&lt;project_id&gt;<br>FIREBASE_PRIVATE_KEY_ID=&lt;private_key_id&gt;<br>FIREBASE_PRIVATE_KEY=&lt;private_key_from_service_account&gt;<br>FIREBASE_CLIENT_EMAIL=&lt;client_email_from_service_account&gt;<br>FIREBASE_CLIENT_ID=&lt;client_id_from_service_account&gt;</pre><p>Notes:</p><ul><li>If your private key contains actual newlines, replace them with \n in .env.</li><li>Set USE_FIREBASE_STORAGE=False locally if you prefer filesystem storage.</li></ul><h3>4) Update Django Settings</h3><p>Your settings.py already includes the required configuration using django-environ and a conditional DEFAULT_FILE_STORAGE switch. Key parts:</p><pre># Base toggle and credentials<br>USE_FIREBASE_STORAGE = env.bool(&#39;USE_FIREBASE_STORAGE&#39;, default=False)<br>FIREBASE_STORAGE_BUCKET = env.str(&#39;FIREBASE_STORAGE_BUCKET&#39;, default=&#39;&#39;)<br>FIREBASE_PROJECT_ID = env.str(&#39;FIREBASE_PROJECT_ID&#39;, default=&#39;&#39;)<br>FIREBASE_PRIVATE_KEY_ID = env.str(&#39;FIREBASE_PRIVATE_KEY_ID&#39;, default=&#39;&#39;)<br>FIREBASE_PRIVATE_KEY = env.str(&#39;FIREBASE_PRIVATE_KEY&#39;, default=&#39;&#39;)<br>FIREBASE_CLIENT_EMAIL = env.str(&#39;FIREBASE_CLIENT_EMAIL&#39;, default=&#39;&#39;)<br>FIREBASE_CLIENT_ID = env.str(&#39;FIREBASE_CLIENT_ID&#39;, default=&#39;&#39;)<br><br>if USE_FIREBASE_STORAGE and FIREBASE_STORAGE_BUCKET:<br>    DEFAULT_FILE_STORAGE = &#39;app_storages.firebase_storage.FirebaseStorage&#39;<br>STORAGES = {<br>    &#39;default&#39;: {<br>        &#39;BACKEND&#39;: DEFAULT_FILE_STORAGE<br>    },<br>}</pre><p>This means when USE_FIREBASE_STORAGE=True and a bucket is provided, Django’s default storage becomes the custom Firebase backend.</p><h3>5) Create the Firebase Storage Backend</h3><p>Create app_storages/firebase_storage.py (already present in this repo). It defines a deconstructible class FirebaseStorage that:</p><ul><li>Initializes the Firebase Admin SDK from env vars</li><li>Uploads files to your bucket</li><li>Generates signed URLs via generate_signed_url</li><li>Supports exists, delete, listdir, size, and time metadata helpers</li></ul><p>Key behaviors to know:</p><ul><li>_save makes uploaded files public by default using blob.make_public().</li><li>url(https://medium.com/name) and signed_url(https://medium.com/name) can return short-lived access URLs.</li><li>Helper firebase_upload_path(instance, filename) builds date-based paths: storage/&lt;model&gt;/&lt;YYYY&gt;/&lt;MM&gt;/&lt;DD&gt;/&lt;filename&gt;.</li></ul><h3>6) Use It in Your Models</h3><p>If Firebase storage is the default, you can use ImageField or FileField as usual.</p><p>Example using the provided firebase_upload_path helper:</p><pre>from django.db import models<br>from app_storages.firebase_storage import firebase_upload_path<br><br>class Profile(models.Model):<br>    avatar = models.ImageField(upload_to=firebase_upload_path, blank=True, null=True)</pre><p>When USE_FIREBASE_STORAGE=True, files uploaded via admin, forms, or DRF will go to Firebase Storage automatically.</p><h3>7) Programmatic Uploads (Views/Services)</h3><pre>from django.core.files.storage import default_storage<br><br><br>def save_bytes(path: str, data: bytes, content_type: str | None = None):<br>    # path example: &quot;uploads/docs/readme.txt&quot;<br>    name = default_storage.save(path, data)<br>    url = default_storage.url(https://medium.com/name)<br>    return name, url</pre><p>For signed access:</p><pre>from app_storages.firebase_storage import get_firebase_storage<br><br>storage = get_firebase_storage()<br>signed = storage.signed_url(https://medium.com/&#39;path/in/bucket.ext&#39;,%20expiration=3600)  # 1 hour</pre><h3>8) Local Development vs Production</h3><ul><li>Local development: set USE_FIREBASE_STORAGE=False to store files on the local filesystem (mediafiles/).</li><li>Production: set USE_FIREBASE_STORAGE=True with valid Firebase env vars.</li><li>Static files are still served by WhiteNoise in this project; Firebase is for user-uploaded media.</li></ul><h3>9) Security &amp; Best Practices</h3><ul><li>Never commit raw service account JSON or secrets to version control.</li><li>Restrict your service account permissions to only what’s needed for Storage.</li><li>Prefer signed URLs over public blobs for private assets.</li><li>Rotate keys if they’re exposed.</li></ul><h3>10) Troubleshooting</h3><ul><li>Files not uploading</li><li>Check USE_FIREBASE_STORAGE and FIREBASE_STORAGE_BUCKET values.</li><li>Verify private key formatting. In .env, newlines must be \n.</li><li>Confirm the bucket exists and your service account has access.</li><li>Getting permission errors</li><li>Ensure the service account has Storage Object Admin on the bucket.</li><li>Wrong URLs or 404s</li><li>Ensure the blob path matches your upload_to logic.</li><li>For signed URLs, ensure system time is correct and expiration is in the future.</li></ul><h3>11) Useful References</h3><ul><li>Firebase Admin SDK (Python): <a href="https://firebase.google.com/docs/admin/setup">https://firebase.google.com/docs/admin/setup</a></li><li>Google Cloud Storage Python Client: <a href="https://cloud.google.com/python/docs/reference/storage/latest">https://cloud.google.com/python/docs/reference/storage/latest</a></li><li>Django File Storage: <a href="https://docs.djangoproject.com/en/stable/topics/files/">https://docs.djangoproject.com/en/stable/topics/files/</a></li></ul><h3>12) Quick Checklist</h3><ul><li>Install firebase-admin and django-environ</li><li>Add .env with Firebase credentials and USE_FIREBASE_STORAGE=True</li><li>Ensure app_storages.FirebaseStorage is active via settings.py</li><li>Use upload_to=firebase_upload_path in your models (optional but recommended)</li><li>Deploy and test an upload (admin/DRF/form)</li></ul><h3><strong>Code:</strong></h3><blockquote>firebase_storage.py</blockquote><pre># {root_project}/app_storages/firebase_storage.py<br><br>import os<br>from datetime import datetime, timedelta, timezone<br>from django.core.files.storage import Storage<br>from django.core.files.base import ContentFile<br>from django.utils.deconstruct import deconstructible<br>import firebase_admin<br>from firebase_admin import credentials, storage<br><br>from django.conf import settings<br><br>@deconstructible<br>class FirebaseStorage(Storage):<br>    &quot;&quot;&quot;<br>    Custom storage backend for Firebase Storage using Firebase Admin SDK<br>    &quot;&quot;&quot;<br><br>    def __init__(self, bucket_name=None):<br>        self.bucket_name = bucket_name or settings.FIREBASE_STORAGE_BUCKET<br>        self._bucket = None<br>        self._initialize_firebase()<br><br>    def _initialize_firebase(self):<br>        &quot;&quot;&quot;Initialize Firebase Admin SDK if not already initialized&quot;&quot;&quot;<br>        if not firebase_admin._apps:<br>            # Use environment variables for Firebase credentials<br>            print(&#39;Initializing Firebase Admin SDK&#39;)<br>            cred_dict = {<br>                &quot;type&quot;: &quot;service_account&quot;,<br>                &quot;project_id&quot;: settings.FIREBASE_PROJECT_ID,<br>                &quot;private_key_id&quot;: settings.FIREBASE_PRIVATE_KEY_ID,<br>                &quot;private_key&quot;: settings.FIREBASE_PRIVATE_KEY.replace(&#39;\\n&#39;, &#39;\n&#39;),<br>                &quot;client_email&quot;: settings.FIREBASE_CLIENT_EMAIL,<br>                &quot;client_id&quot;: settings.FIREBASE_CLIENT_ID,<br>                &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>                &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,<br>                &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,<br>                &quot;client_x509_cert_url&quot;: f&quot;https://www.googleapis.com/robot/v1/metadata/x509/{settings.FIREBASE_CLIENT_EMAIL}&quot;<br>            }<br><br>            cred = credentials.Certificate(cred_dict)<br>            firebase_admin.initialize_app(cred, {<br>                &#39;storageBucket&#39;: self.bucket_name<br>            })<br><br>    @property<br>    def bucket(self):<br>        &quot;&quot;&quot;Get Firebase storage bucket instance&quot;&quot;&quot;<br>        if self._bucket is None:<br>            self._bucket = storage.bucket()<br>        return self._bucket<br><br>    def _save(self, name, content):<br>        &quot;&quot;&quot;Save file to Firebase Storage&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br><br>        # Read content and upload<br>        if hasattr(content, &#39;read&#39;):<br>            content.seek(0)<br>            blob.upload_from_file(content, content_type=self._guess_content_type(name))<br>        else:<br>            blob.upload_from_string(content, content_type=self._guess_content_type(name))<br><br>        # Make the blob publicly accessible<br>        blob.make_public()<br><br>        return name<br><br>    def _open(self, name, mode=&#39;rb&#39;):<br>        &quot;&quot;&quot;Open file from Firebase Storage&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br><br>        if not blob.exists():<br>            raise FileNotFoundError(f&quot;File {name} not found in Firebase Storage&quot;)<br><br>        # Download as bytes<br>        file_content = blob.download_as_bytes()<br>        return ContentFile(file_content, name=name)<br><br>    def delete(self, name):<br>        &quot;&quot;&quot;Delete file from Firebase Storage&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            blob.delete()<br>        return None<br><br>    def exists(self, name):<br>        &quot;&quot;&quot;Check if file exists in Firebase Storage&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        return blob.exists()<br><br>    def listdir(self, path):<br>        &quot;&quot;&quot;List directories and files in Firebase Storage&quot;&quot;&quot;<br>        if path and not path.endswith(&#39;/&#39;):<br>            path += &#39;/&#39;<br><br>        blobs = list(self.bucket.list_blobs(prefix=path, delimiter=&#39;/&#39;))<br><br>        directories = []<br>        files = []<br><br>        for blob in blobs:<br>            if blob.name.endswith(&#39;/&#39;):<br>                # It&#39;s a directory<br>                dir_name = blob.name[len(path):].rstrip(&#39;/&#39;)<br>                if dir_name:<br>                    directories.append(dir_name)<br>            else:<br>                # It&#39;s a file<br>                file_name = blob.name[len(path):]<br>                if file_name and &#39;/&#39; not in file_name:<br>                    files.append(file_name)<br><br>        return directories, files<br><br>    def size(self, name):<br>        &quot;&quot;&quot;Get file size&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            blob.reload()<br>            return blob.size<br>        raise FileNotFoundError(f&quot;File {name} not found&quot;)<br><br>    def url(https://medium.com/self,%20name,%20expiration=3600):<br>        &quot;&quot;&quot;Get public URL for the file&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            # Generate signed URL with expiration<br>            expiration_time = datetime.now(timezone.utc) + timedelta(seconds=expiration)<br>            return blob.generate_signed_url(https://medium.com/expiration=expiration_time)<br>        return None<br><br>    def signed_url(https://medium.com/self,%20name,%20expiration=3600):<br>        &quot;&quot;&quot;Generate a signed URL for private access&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            # Generate signed URL with expiration<br>            expiration_time = datetime.now(timezone.utc) + timedelta(seconds=expiration)<br>            return blob.generate_signed_url(https://medium.com/expiration=expiration_time)<br>        return None<br><br>    def get_modified_time(self, name):<br>        &quot;&quot;&quot;Get last modified time&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            blob.reload()<br>            return blob.updated<br>        raise FileNotFoundError(f&quot;File {name} not found&quot;)<br><br>    def get_created_time(self, name):<br>        &quot;&quot;&quot;Get creation time&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            blob.reload()<br>            return blob.time_created<br>        raise FileNotFoundError(f&quot;File {name} not found&quot;)<br><br>    def get_accessed_time(self, name):<br>        &quot;&quot;&quot;Get last accessed time (same as modified time for Firebase)&quot;&quot;&quot;<br>        return self.get_modified_time(name)<br><br>    def generate_signed_url(https://medium.com/self,%20name,%20expiration=3600):<br>        &quot;&quot;&quot;Generate a signed URL for private access&quot;&quot;&quot;<br>        blob = self.bucket.blob(name)<br>        if blob.exists():<br>            # Generate signed URL with expiration<br>            expiration_time = datetime.now(timezone.utc) + timedelta(seconds=expiration)<br>            return blob.generate_signed_url(https://medium.com/expiration=expiration_time)<br>        return None<br><br>    def _guess_content_type(self, name):<br>        &quot;&quot;&quot;Guess content type based on file extension&quot;&quot;&quot;<br>        import mimetypes<br>        content_type, _ = mimetypes.guess_type(name)<br>        return content_type or &#39;application/octet-stream&#39;<br><br><br># Convenience function to get a configured Firebase storage instance<br>def get_firebase_storage():<br>    &quot;&quot;&quot;Get a configured Firebase storage instance&quot;&quot;&quot;<br>    return FirebaseStorage()<br><br>def firebase_upload_path(instance, filename):<br>    &quot;&quot;&quot;<br>    Generate upload path for Firebase storage<br>    Format: uploads/{model_name}/{year}/{month}/{day}/{filename}<br>    &quot;&quot;&quot;<br>    from datetime import datetime<br>    now = datetime.now()<br>    model_name = instance.__class__.__name__.lower()<br>    return os.path.join(f&#39;storage/{model_name}/{now.year}/{now.month:02d}/{now.day:02d}/{filename}&#39;)</pre><blockquote>settings.py</blockquote><pre># {project_root}/{settings_folder}/settings.py<br><br># use django environ<br>import environ<br>env = environ.Env()<br>environ.Env.read_env(&#39;.env&#39;)<br><br># update installed apps<br><br>INSTALLED_APPS = [<br>    ...<br>    &#39;app_storages.apps.AppStoragesConfig&#39;,<br>    ...<br>]<br><br>DEFAULT_FILE_STORAGE = &#39;django.core.files.storage.FileSystemStorage&#39;<br><br># Firebase Storage settings<br>USE_FIREBASE_STORAGE = env.bool(&#39;USE_FIREBASE_STORAGE&#39;, default=False)<br>FIREBASE_STORAGE_BUCKET = env.str(&#39;FIREBASE_STORAGE_BUCKET&#39;, default=&#39;&#39;)<br>FIREBASE_PROJECT_ID = env.str(&#39;FIREBASE_PROJECT_ID&#39;, default=&#39;&#39;)<br>FIREBASE_PRIVATE_KEY_ID = env.str(&#39;FIREBASE_PRIVATE_KEY_ID&#39;, default=&#39;&#39;)<br>FIREBASE_PRIVATE_KEY = env.str(&#39;FIREBASE_PRIVATE_KEY&#39;, default=&#39;&#39;)<br>FIREBASE_CLIENT_EMAIL = env.str(&#39;FIREBASE_CLIENT_EMAIL&#39;, default=&#39;&#39;)<br>FIREBASE_CLIENT_ID = env.str(&#39;FIREBASE_CLIENT_ID&#39;, default=&#39;&#39;)<br><br>if USE_FIREBASE_STORAGE and FIREBASE_STORAGE_BUCKET:<br>    print(&#39;using firebase&#39;)<br>    # Use Firebase Storage in production<br>    DEFAULT_FILE_STORAGE = &#39;app_storages.firebase_storage.FirebaseStorage&#39;<br><br>STORAGES = {<br>    &#39;default&#39;: {<br>        &#39;BACKEND&#39;: DEFAULT_FILE_STORAGE<br>    }<br>}</pre><p><strong>Find me:</strong> <a href="https://imtipu.me/">https://imtipu.me</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=613a9451a6a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django: How to check/show a user liked a post or not in List View without Duplicate Queries.]]></title>
            <link>https://imtipu.medium.com/django-how-to-check-show-user-liked-a-post-or-not-in-list-view-without-duplicate-queries-f26171b26f88?source=rss-fe182178a316------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26171b26f88</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Borhan Tipu]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 18:12:40 GMT</pubDate>
            <atom:updated>2022-01-07T18:13:48.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q5LRKygBH_SXMikgcQstQ.jpeg" /></figure><p>Create a model if you don’t have:</p><pre><em>class </em>PostLike(models.Model):<em><br>    </em>user = models.ForeignKey(&#39;users.User&#39;, on_delete=models.CASCADE, related_name=&#39;post_likes&#39;)<br>    post = models.ForeignKey(&#39;posts.Post&#39;, on_delete=models.CASCADE, related_name=&#39;likes&#39;)<br><br>    created = models.DateTimeField(auto_now_add=<em>True</em>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4nlGNLiRBho-86pOn-NXQ.png" /><figcaption>Model</figcaption></figure><p><strong>Code for Rest Framework</strong></p><p>Create a Model Serializer for Post Model. is_liked will be Boolean field and read only.</p><pre><em>class </em>PostSerializer(serializers.ModelSerializer):<br>    is_liked = serializers.BooleanField(read_only=<em>True</em>)<br>    <em>class </em>Meta:<br>      model = Post<br>      fields = &#39;__all__&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8xR2oUXfW-zHhmNRfTMbg.png" /></figure><p>Create a Rest ListAPIView PostListAPIView . Use authentication class to get the request.user .</p><pre><em>from </em>django.db.models <em>import </em>Prefetch, Exists, OuterRef<br><br><em>class </em>PostListAPIView(ListAPIView):<br>    serializer_class = PostSerializer<br>    queryset = Post.objects.none()<br><br>    <em>def </em>get_queryset(<em>self</em>):<br>        <em>return </em>Post.objects \<br>            .annotate(is_liked=Exists(PostLike.objects.filter(<br>            user=<em>self</em>.request.user, post_id=OuterRef(&#39;pk&#39;)))) \<br>            .order_by(&#39;title&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMo_8NiTeqv2B4Od5OHKcQ.png" /><figcaption>List API View</figcaption></figure><p>That’s it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26171b26f88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Rest Framework Customize Pagination]]></title>
            <link>https://imtipu.medium.com/django-rest-framework-customize-pagination-e2334544256d?source=rss-fe182178a316------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2334544256d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Borhan Tipu]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 02:51:00 GMT</pubDate>
            <atom:updated>2021-04-30T02:51:00.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*R2R6TH-ZcU0ltCUBRXjPrA.gif" /></figure><p>Customize your pagination and return more data in API response for List View</p><p>Install Django Rest Framework by pip install djangorestframework or pipenv install djangorestframework</p><p>Create a new Model Serializer in app/api/serializers.py file like:</p><pre><strong><em># app/api/serializers.py</em></strong><em><br>from </em>rest_framework <em>import </em>serializers<br><em>from </em>app.models <em>import </em>Blog<br><br><br><em>class </em>BlogSerializer(serializers.ModelSerializer):<br>    <em>class </em>Meta:<br>        model = Blog<br>        fields = &#39;__all__&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQJ3rlYuywGTVneHNhf_Ng.png" /><figcaption><strong><em>app/api/serializers.py</em></strong></figcaption></figure><p>Create a new Model ViewSet in app/api/viewsets.py like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLNSLd60rnjINC-p_1rUOg.png" /><figcaption><strong>app/api/viewsets.py</strong></figcaption></figure><pre><strong><em># </em></strong><strong>app/api/viewsets.py</strong><em><br>class </em>BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [IsAuthenticated, ] <strong># remove if not required</strong><br>    authentication_classes = [JWTAuthentication, SessionAuthentication] <strong># remove if not required</strong><br>    serializer_class = BlogSerializer<br>    queryset = Blog.objects.all()</pre><p>Now Create a pagination class in app/api/paginations.py like:</p><pre><strong># </strong><strong>app/api/paginations.py</strong><br>from rest_framework.pagination import PageNumberPagination<br>from rest_framework.response import Response</pre><pre>class CustomPagination(PageNumberPagination):<br>  pass</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d13Hvyx_GNgBADj6jVnlZg.png" /><figcaption><strong>app/api/paginations.py</strong></figcaption></figure><p>Now add default pagination class in Django Settings for Rest Framwork</p><pre># project/settings.py<br># default setup<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.PageNumberPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 20<br>}</pre><pre># change default pagination class to you custom class<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;app.api.paginations.CustomPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 20 # we can make it dynamic from class. But, set a number as default<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awRrP-Pd7swi3R-2kfvxsQ.png" /><figcaption><strong>project/settings.py</strong></figcaption></figure><p>Now we will add more option in Pagination class. Default example response will be like</p><pre>HTTP 200 OK<br>{<br>    &quot;count&quot;: 1023<br>    &quot;next&quot;: &quot;<a href="https://api.example.org/accounts/?page=5">https://api.example.org/accounts/?page=5</a>&quot;,<br>    &quot;previous&quot;: &quot;<a href="https://api.example.org/accounts/?page=3">https://api.example.org/accounts/?page=3</a>&quot;,<br>    &quot;results&quot;: [<br>       …<br>    ]<br>}</pre><p>Here is my full custom pagination class</p><pre>from rest_framework.pagination import PageNumberPagination<br>from rest_framework.response import Response<br>import math<br>## you can override page_size, max_page_size from url query params \<br>## to make it more dynamic<br>class CustomPagination(PageNumberPagination):<br>    page_size = 20 # default page size<br>    max_page_size = 1000 # default max page size<br>    page_size_query_param = &#39;page_size&#39; # if you want to dynamic items per page from request you must have to add it <br>      <br>    def get_paginated_response(self, data):<br>        # if you want to show page size in resposne just add these 2 lines<br>        if self.request.query_params.get(&#39;page_size&#39;):<br>            self.page_size = int(self.request.query_params.get(&#39;page_size&#39;))<br>            <br>        # you can count total page from request by total and page_size<br>        total_page = math.ceil(self.page.paginator.count / self.page_size)<br>        <br>        # here is your response<br>        return Response({<br>            &#39;count&#39;: self.page.paginator.count,<br>            &#39;total&#39;: total_page,<br>            &#39;page_size&#39;: self.page_size,<br>            &#39;current&#39;: self.page.number,<br>            &#39;previous&#39;: self.get_previous_link(),<br>            &#39;next&#39;: self.get_next_link(),<br>            &#39;results&#39;: data<br>        })</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRmWxDhCmXVvI6vwj0ww4w.png" /><figcaption>CustomPagination class</figcaption></figure><p>You can set this pagination class for all as default from settings file or you can use it to you viewsets and list views.</p><pre>class BlogViewSet(viewsets.ModelViewSet):<br>    serializer_class = BlogSerializer<br>    queryset = Blog.objects.all()<br>    pagination_class = CustomPagination</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfYYpAzIxz2XEOuw0T2aBQ.png" /></figure><p>That’s it. <br>It should work now. If you need any help with Django let me know</p><p>Visit: <a href="https://imtipu.me/">imtipu.me</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2334544256d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Debug Toolbar Loaded but not showing/appearing, Fix it and Bring it Back.]]></title>
            <link>https://imtipu.medium.com/django-debug-toolbar-loaded-but-not-showing-appearing-fix-it-and-bring-it-back-7dba91ccecec?source=rss-fe182178a316------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dba91ccecec</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-debug-toolbar]]></category>
            <dc:creator><![CDATA[Borhan Tipu]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 11:37:29 GMT</pubDate>
            <atom:updated>2025-11-30T05:29:08.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVPl6Gvh9S1HX6i6xkqIIg.png" /></figure><p><strong>*Are you facing the problem with Django Debug Toolbar showing up?*<br>I faced too…</strong></p><p>Here I will show you how I fixed it….</p><p>Install <strong><em>Debug Toolbar</em></strong>…<br>For virtual env: pip install django-debug-toolbar <br>For Pipenv: pipenv install django-debug-toolbar <br>Link: <a href="https://pypi.org/project/django-debug-toolbar/"><strong>https://pypi.org/project/django-debug-toolbar/</strong></a><strong><br></strong>Docs: <a href="https://django-debug-toolbar.readthedocs.io/en/latest/"><strong>https://django-debug-toolbar.readthedocs.io/en/latest/</strong></a></p><p>Go to <strong><em>settings.py</em></strong> and add to <strong>INSTALLED_APPS</strong></p><pre>INSTALLED_APPS = [<br> <em># …</em><br> ‘django.contrib.staticfiles’,<br> <em># … not for debug mode</em><br> ‘debug_toolbar’,<br>]</pre><pre>STATIC_URL = ‘/static/’</pre><p>The Debug Toolbar should have appeared only in Debug mode. So, the rest of the settings will be for DEBUG mode only.</p><pre><em># </em>debug_toolbar moved here. <em><br>if </em>DEBUG:<br>    MIDDLEWARE += [<br>        &#39;debug_toolbar.middleware.DebugToolbarMiddleware&#39;,<br>    ]<br>    INSTALLED_APPS += [<br>        &#39;debug_toolbar&#39;,<br>    ]<br>    INTERNAL_IPS = [&#39;127.0.0.1&#39;, ]<br><br>    # this is the main reason for not showing up the toolbar<br>    <em>import </em>mimetypes<br>    mimetypes.add_type(&quot;application/javascript&quot;, &quot;.js&quot;, <em>True</em>)<br><br>    DEBUG_TOOLBAR_CONFIG = {<br>        &#39;INTERCEPT_REDIRECTS&#39;: <em>False</em>,<br>    }</pre><p>Update your {project}/urls.py file.</p><pre><em>from </em>django.conf <em>import </em>settings<br><em>from </em>django.urls <em>import </em>path, include</pre><pre>urlpatterns = [<br>  path(&quot;admin/&quot;, admin.site.urls),<br>]</pre><pre># add debug toolbar in urlpatterns<br><em>if </em>settings.DEBUG:<br>    <em>import </em>debug_toolbar<br>    urlpatterns += [<br>        path(&#39;__debug__/&#39;, include(debug_toolbar.urls)),<br>    ]</pre><p>The main reason for not showing up the toolbar is because of the javascript <strong>mime-types</strong> error when you connect the <strong>debug_toolbar<br></strong>If the already added to your application then just add two lines of code in your <strong>settings.py </strong>file.</p><pre>mimetypes<br>mimetypes.add_type(&quot;application/javascript&quot;, &quot;.js&quot;, <em>True</em>)</pre><p>Now the debug toolbar should be visible in Debug mode.</p><p>If you need any help with Full-Stack Development with Django and Shopify, feel free to contact me anytime.<br>Visit: <a href="http://imtipu.me/"><strong>imtipu.me</strong></a></p><p>Contact if you need any help with Django and Shopify</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dba91ccecec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Shopify Webhook HMAC Verify]]></title>
            <link>https://imtipu.medium.com/django-shopify-webhook-hmac-verify-bf6f23e992c1?source=rss-fe182178a316------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf6f23e992c1</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Borhan Tipu]]></dc:creator>
            <pubDate>Thu, 28 May 2020 17:47:28 GMT</pubDate>
            <atom:updated>2021-12-07T22:19:23.961Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will show you how you can verify Shopify Webhook Hmac in a Django Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*97ktj-p8r76OrtGhk55ZIA.png" /></figure><p><strong>In Shopify:</strong><br> Go to <strong>Settings &gt; Notifications &gt; Webhook<br></strong>1. Create a Webhook<br>2. Add Webhook URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*0YjHPThLMVVLdoQpFyAD2A.png" /><figcaption>Create Webhook</figcaption></figure><p>You can use <strong>ngrok </strong>for development and testing purpose</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*tsg66P6JY4ul6Wp_qvZwvA.png" /><figcaption>SHOPIFY_WEBHOOK_SIGNED_KEY</figcaption></figure><p>After adding the webhook URL you will find a Signed Key for webhook just below of the Webhook URL list.</p><p><strong>In Django:</strong><br>Add a variable in <strong>settings.py </strong>file</p><pre>SHOPIFY_WEBHOOK_SIGNED_KEY = env.str(&#39;SHOPIFY_WEBHOOK_SIGNED_KEY&#39;, &#39;&#39;)</pre><p>Then in your <strong>views.py </strong>file,<br>I used <strong>django-rest-framework</strong> views, response, and status.</p><pre><em>from </em>django.views.decorators.csrf <em>import </em>csrf_exempt<br><em>from </em>rest_framework <em>import </em>status<br><em>from </em>rest_framework.decorators <em>import </em>api_view<br>from rest_framework import status<br><em>from </em>rest_framework.response <em>import </em>Response</pre><pre><em>import </em>hmac<br><em>import </em>hashlib<br><em>import </em>base64</pre><pre>def computed_hmac(secret, body):<br>    hash_code = hmac.new(secret.encode(&#39;utf-8&#39;), body, hashlib.sha256)<br>    return base64.b64encode(hash_code.digest()).decode()</pre><pre>def verify_hmac(secret, body, shopify_hmac):<br>    return computed_hmac(secret, body) == shopify_hmac</pre><pre><a href="http://twitter.com/csrf_exempt">@csrf_exempt</a><br><a href="http://twitter.com/api_view">@api_view</a>([&#39;POST&#39;])<br>def api_view_webhook(request):</pre><pre># get hmac from shopify webhook request<br>    shopify_hmac = request.headers.get(&#39;X-Shopify-Hmac-Sha256&#39;)<br>    if verify_hmac(settings.SHOPIFY_WEBHOOK_SIGNED_KEY, request.body, shopify_hmac):<br>        print(&#39;valid&#39;)<br>        return Response(status=status.HTTP_200_OK)</pre><pre>    else:<br>        print(&#39;invalid&#39;)<br>    return Response(status=status.HTTP_400_BAD_REQUEST)</pre><p>In your <strong>urls.py</strong> file,</p><pre><em>from </em>.views <em>import </em>api_view_webhook</pre><pre>urlpatterns = [<br>    path(&#39;webhook/&#39;, api_view_webhook, name=&#39;api_view_webhook&#39;),<br>]</pre><p>If <strong>verify_hmac </strong>is <strong>True </strong>then it will print <strong>“valid”</strong> in terminal console otherwise it will print <strong>“invalid”. <br></strong>That’s it.</p><p>Visit: <a href="http://imtipu.me/">imtipu.me</a></p><p>Contact if you need any help with Django and Shopify<br>Skype: me@imtipu.me</p><p>Email: <a href="http://mailto:me@imtipu.me/">me@imtipu.me</a></p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf6f23e992c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>