<?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 Erdi Mollahüseyinoğlu on Medium]]></title>
        <description><![CDATA[Stories by Erdi Mollahüseyinoğlu on Medium]]></description>
        <link>https://medium.com/@erdimollahseyin?source=rss-6c8dafd882a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NVWHsfgM7Ftb3R8Gyd00CQ.png</url>
            <title>Stories by Erdi Mollahüseyinoğlu on Medium</title>
            <link>https://medium.com/@erdimollahseyin?source=rss-6c8dafd882a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:58:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erdimollahseyin/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[Django Query Optimizations: Speed Up Your App Efficiently]]></title>
            <link>https://medium.com/analytics-vidhya/django-query-optimizations-how-to-make-your-app-faster-eb4b25877dce?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb4b25877dce</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database-efficiency]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[performance-tuning]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 12:03:08 GMT</pubDate>
            <atom:updated>2025-03-27T19:24:57.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*98jhy8dL43yrwvPVpJDpbQ.jpeg" /></figure><p>Django is a powerful and easy-to-use web framework based on Python. Developers can quickly perform database operations using Django’s ORM (Object-Relational Mapping) tool. However, as database queries become more complex and the application’s traffic increases, poorly configured queries can significantly affect the application’s performance.</p><p>Although Django’s ORM system simplifies queries, neglecting database optimization can create unnecessary load on the database. Especially in large projects, issues like N+1 queries, unnecessary data retrieval, and missing indexes can slow down the application. This can negatively impact the user experience and the overall efficiency of the application.</p><p>In this article, we will explore how to optimize database queries in Django applications. We will look into the powerful tools and methods provided by Django to speed up database queries and improve performance. Our goal is to avoid unnecessary query loads, make your application faster, and manage your database operations in the most efficient way.</p><p>If you’re ready, let’s start examining step by step how to make your database queries faster in Django.</p><h3>N+1 Query Problem</h3><p>One of the most common performance issues in Django is the N+1 query problem. This occurs when separate queries are sent for each related object, which can lead to a significant increase in the number of database queries being executed. For example, when you retrieve a list of objects and then access related objects for each of them, Django may issue a separate query for each related object.</p><p>You can solve this problem by using <strong>select_related</strong> and <strong>prefetch_related</strong>. Both of these methods are designed to optimize the number of queries by preloading related objects.</p><ul><li><strong>select_related</strong>: This method is used for <strong>ForeignKey</strong> and <strong>OneToOne</strong> relationships. It performs a SQL join and retrieves the related objects in a single query. In this example, Django will fetch all the blogs and their related authors in one query by using an SQL JOIN. Also, using iterator() to fetch database records in chunks helps save memory by avoiding loading all data at once, which is ideal for handling large datasets.</li></ul><pre># Without select_related (N+1 problem)<br>for blog_obj in Blog.objects.iterator():<br>    print(blog_obj.title, blog_obj.author.get_full_name())<br><br># With select_related (1 Query)<br>for blog_obj in Blog.objects.select_related(&#39;author&#39;).iterator():<br>    print(blog_obj.title, blog_obj.author.get_full_name())</pre><ul><li><strong>prefetch_related</strong>: This method is used for <strong>ManyToMany</strong> and <strong>reverse ForeignKey</strong> relationships. It performs a separate query for each related model and then does the “joining” in Python rather than in the database. This can be more efficient when dealing with multiple related objects. Here, Django will first fetch all blogs and then fetch all related genres in a separate query, reducing the number of queries from N+1 to just 2 queries. By using select_related and prefetch_related, you can reduce the number of queries and significantly improve the performance of your application, especially when dealing with large datasets or multiple relationships.</li></ul><pre># Without prefetch_related (N+1 problem)<br>author_qs = Author.objects.all()<br>authors = []<br>for author_obj in author_qs:<br>    blogs = [blog_obj.title for blog_obj in author_obj.blogs.all()]<br>    authors.append({<br>        &#39;name&#39;: author_obj.get_full_name(),<br>        &#39;blogs&#39;: blogs<br>    })<br><br># # With prefetch_related (2 Query)<br>author_qs = Author.objects.prefetch_related(&#39;blogs&#39;)<br>authors = []<br>for author_obj in author_qs:<br>    blogs = [blog_obj.title for blog_obj in author_obj.blogs.all()]<br>    authors.append({<br>        &#39;name&#39;: author_obj.get_full_name(),<br>        &#39;blogs&#39;: blogs<br>    })</pre><p><strong><em>Lazy Loading vs. Eager Loading:</em></strong></p><p>In Django ORM, relationships are typically loaded lazily by default, which means related objects are not fetched until they are accessed. While this is often useful for performance in cases where related objects might not be needed, it can lead to the N+1 query problem when multiple objects with related data are accessed in a loop. This is where <strong>eager loading</strong> comes into play.</p><ul><li><strong>Lazy Loading</strong>: This approach fetches related objects only when they are accessed, potentially leading to multiple queries for each related object when iterating through a list of objects.</li><li><strong>Eager Loading</strong>: This approach, using select_related or prefetch_related, loads all related objects in advance with a single query, preventing the N+1 query problem.</li></ul><p>Both loading strategies have their use cases:</p><ul><li><strong>Lazy loading</strong> works well when you don’t always need related data.</li><li><strong>Eager loading</strong> is more efficient when you know you’ll need the related data upfront, like in cases where you need to display a list of blogs with their authors.</li></ul><h3>Reducing Database Query Count</h3><p>In Django, optimizing database queries is crucial for improving application performance, especially when dealing with large amounts of data. Below are two important techniques to reduce database query count:</p><p><strong><em>Using bulk_create and bulk_update for Efficient Data Insertion and Updates:</em></strong></p><p>When working with large datasets, inserting or updating many records one at a time can result in a large number of database queries, which can severely impact performance. Instead, you can use <strong>bulk_create</strong> and <strong>bulk_update</strong> to batch these operations.</p><ul><li><strong>bulk_create</strong>: Allows you to insert multiple records into the database in a single query. This method is useful when you need to add many objects at once.</li></ul><pre>blogs_to_create = [<br>    Blog(title=”Blog 1&quot;, author=”Author A”),<br>    Blog(title=”Blog 2&quot;, author=”Author B”),<br>    Blog(title=”Blog 3&quot;, author=”Author C”)<br>]<br>Blog.objects.bulk_create(blogs_to_create)</pre><p>In this example, instead of executing separate queries for each Blog object, <strong>bulk_create</strong> inserts all blogs in a single query, improving performance.</p><ul><li><strong>bulk_update</strong>: Allows you to update multiple records in a single query. This is particularly useful when updating several objects with similar changes.</li></ul><pre>blog_qs = Blog.objects.filter(author=&quot;Author A&quot;)<br>for blog_obj in blog_qs:<br>    blog_obj.title = &quot;Updated Title&quot;<br>Blog.objects.bulk_update(blog_qs, [&#39;title&#39;])</pre><p>Here, <strong>bulk_update</strong> allows you to update multiple blogs with the same field in a single query, reducing the number of database operations.</p><p><strong><em>Using defer() and only() to Prevent Unnecessary Data Retrieval:</em></strong></p><p>In some cases, you may not need all the fields of a model when querying the database. Fetching unnecessary fields can increase memory usage and reduce performance. The <strong>defer()</strong> and <strong>only()</strong> methods allow you to limit the fields retrieved from the database.</p><ul><li><strong>only()</strong>: This method fetches only the specified fields, which can help reduce the amount of data transferred from the database.</li></ul><pre># Fetch only specific fields<br>blog_qs = Blog.objects.only(&#39;title&#39;, &#39;author&#39;)</pre><p>In this example, only the <strong>title</strong> and <strong>author</strong> fields of the Blog model will be fetched from the database, preventing unnecessary data from being retrieved.</p><ul><li><strong>defer()</strong>: This method is the opposite of <strong>only()</strong>. It retrieves all fields except the ones specified, delaying the retrieval of those deferred fields until they are actually accessed.</li></ul><pre># Defer loading of specific fields<br>blog_qs = Blog.objects.defer(&#39;description&#39;)</pre><p>In this example, all fields except for <strong>description</strong> will be fetched initially. The <strong>description</strong> field will only be queried when it is accessed, reducing the initial query load.</p><p><strong><em>Using distinct:</em></strong></p><p>When querying data that might have duplicate rows due to joins or other reasons, you can use the distinct() method to eliminate duplicates. This is especially helpful when you&#39;re working with many-to-many relationships or queries that return redundant data.</p><pre># Without distinct(), there could be duplicate authors if a blog has multiple tags.<br>blog_qs = Blog.objects.prefetch_related(&#39;tags&#39;).filter(tags__name=&#39;Django&#39;)<br><br># Using distinct() to remove duplicates.<br>blog_qs = Blog.objects.prefetch_related(&#39;tags&#39;).filter(tags__name=&#39;Django&#39;).distinct(&#39;title&#39;)</pre><p>In this case, distinct(&#39;title&#39;) ensures that only unique blog titles are returned, eliminating any duplicate entries due to repeated tags.</p><p><strong><em>Using Q:</em></strong></p><p>The Q() object allows you to write complex queries that involve <strong>OR</strong> conditions. It&#39;s particularly useful when you need to query based on multiple conditions but don&#39;t want to limit the query to just one field.</p><p>Example with Q():</p><pre>from django.db.models import Q<br><br># Querying blogs where the title contains &#39;Python&#39; OR the description contains &#39;Django&#39;<br>blog_qs = Blog.objects.filter(<br>    Q(title__icontains=&#39;Python&#39;) | Q(description__icontains=&#39;Django&#39;)<br>)</pre><p>This query will return blogs that have either ‘Python’ in their title or ‘Django’ in their description. The Q() object can be chained together with | (OR) or &amp; (AND) operators to create more complex queries.</p><p><strong><em>Using exists:</em></strong></p><p>The exists() method checks if any objects match the query without loading the entire object or collection, making it more efficient.</p><pre><br># Inefficient<br>if Author.objects.filter(name=&quot;Dani Alves&quot;).count() &gt; 0:<br>    print(&quot;Author exists!&quot;)<br><br># Efficient<br>if Author.objects.filter(name=&quot;Dani Alves&quot;).exists():<br>    print(&quot;Author exists!&quot;)</pre><p>This checks if an author with the name “Dani Alves” exists.</p><p><strong><em>Using aggregate:</em></strong></p><p>Aggregation collects data from multiple rows to return a single summary value, such as totals, averages, minimums, or maximums. Django’s aggregate() function allows you to perform these calculations across a queryset.</p><p>When to Use Aggregation:</p><ul><li><strong>Calculating Summaries</strong>: For example, calculating the total number of comments from all blogs.</li><li><strong>Global Calculations</strong>: When you need to calculate a result across multiple rows or the entire dataset.</li></ul><pre><br>total_comments = Blog.objects.aggregate(total_comments=Count(&#39;comments&#39;))[&#39;total_comments&#39;]</pre><p><strong><em>Using annotate:</em></strong></p><p>When you need to perform aggregations (such as counting, averaging, etc.) on a queryset, Django’s annotate() function can be used. This method is particularly useful when you need to include additional calculated fields in your query result, such as the total number of related objects for a model.</p><p>Example with annotate():</p><pre>from django.db.models import Count<br><br># Count the number of comments for each blog<br>blog_qs = Blog.objects.annotate(comment_count=Count(&#39;comments&#39;))<br><br># Retrieve blogs where the number of comments is greater than 10<br>blog_qs_with_more_than_10_comments = blog_qs.filter(comment_count__gt=10)</pre><p>In this example, the annotate() method adds a comment_count to each Blog object, representing the total number of comments related to that blog. After annotating the queryset, you can use it in filtering or sorting.</p><p><strong><em>Using Django Extensions and </em></strong><strong><em>shell_plus for Query Inspection:</em></strong></p><p>Django Extensions is a popular third-party package that enhances Django’s shell capabilities. One of the most useful features is shell_plus, which is an improved version of Django&#39;s default shell. It automatically imports models and other commonly used utilities, making it easier to work with your models and queries in the interactive shell.</p><p>Using shell_plus can help you quickly inspect your queries and optimize them without writing too much code. It’s especially helpful for testing different query strategies like select_related or prefetch_related, and for reviewing the number of queries being executed in real-time.</p><p>To install Django Extensions, you first need to add it to your project:</p><pre>pip install django-extensions</pre><p>Then, add it to your INSTALLED_APPS in settings.py:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;django_extensions&#39;,<br>]</pre><p>With django_extensions installed, you can run shell_plus instead of the regular shell command:</p><pre>python manage.py shell_plus</pre><p>This opens an interactive shell where all your models and frequently used functions are automatically imported.</p><p>Here’s an example of how you can test the number of queries being executed when accessing related objects:</p><pre># Using select_related to reduce queries for related authors<br>from blog.models import Blog<br>from django.db import connection<br><br># Inspect the number of queries before fetching blogs<br>print(f&quot;Queries before: {len(connection.queries)}&quot;)<br><br>blog_qs = Blog.objects.select_related(&#39;author&#39;).all()<br><br># Inspect the number of queries after fetching blogs<br>print(f&quot;Queries after: {len(connection.queries)}&quot;)<br><br># Print all queries executed during this operation<br>for query in connection.queries:<br>    print(query[&#39;sql&#39;])</pre><p>In this example, you can use select_related to optimize the number of queries when retrieving blogs and related authors. By inspecting the queries before and after executing the code, you can easily check if the optimization is working and how many queries are being fired.</p><h3>Indexing and Database Design</h3><p>Indexing is an essential technique to speed up database queries by allowing the database to locate and retrieve data more efficiently. When used correctly, indexes can significantly improve query performance, especially for large datasets. However, improper use or overuse of indexes can negatively impact performance, so it’s essential to know when and where to apply them.</p><pre>class Blog(models.Model):<br>    title = models.CharField(max_length=255)<br>    author = models.ForeignKey(<br>        to=Author, <br>        on_delete=models.CASCADE,<br>        related_name=&#39;blogs&#39;,<br>    )<br>    published_date = models.DateField()<br><br>    class Meta:<br>        indexes = [<br>            models.Index(fields=[&#39;title&#39;]),  # Index on the &#39;title&#39; field<br>            models.Index(fields=[&#39;author&#39;]),  # Index on the &#39;author&#39; field<br>        ]</pre><p>In this example, an index is created on the <strong>title</strong> field to speed up queries that filter by blog title. Additionally, an index is created on the <strong>author</strong> field to speed up queries that filter by author.</p><p><strong><em>Using unique:</em></strong></p><p>A <strong>UNIQUE</strong> index ensures that all the values in the indexed column are distinct. This is commonly used for fields that require unique values, such as emails or usernames.</p><pre>class User(models.Model):<br>    username = models.CharField(<br>        max_length=150, <br>        unique=True<br>    )<br>    email = models.EmailField(unique=True)</pre><p>Here, both the username and email fields are indexed to ensure no two users have the same username or email.</p><p><strong><em>Using GIN:</em></strong></p><p>A <strong>GIN</strong> index is particularly useful for indexing fields that contain large amounts of text data or array-like data (such as TextField or ArrayField in PostgreSQL). This type of index is optimized for searching through full-text data or arrays.</p><p>Example with PostgreSQL:</p><pre>from django.contrib.postgres.fields import ArrayField<br>from django.db import models<br><br>class Blog(models.Model):<br>    title = models.CharField(max_length=255)<br>    tags = ArrayField(models.CharField(max_length=50))<br><br>    class Meta:<br>        indexes = [<br>            models.Index(fields=[&#39;tags&#39;], name=&#39;tags_gin_idx&#39;, opclasses=[&#39;gin&#39;])  # GIN index on &#39;tags&#39;<br>        ]</pre><p>In this example, a <strong>GIN</strong> index is applied on the tags field, which helps improve search performance when querying on array elements.</p><h3>Queryset Caching and Prefetching</h3><p>Caching is a powerful technique that helps speed up the retrieval of frequently used data by storing query results temporarily. When your Django application repeatedly executes the same queries, caching can help improve performance by avoiding repeated database hits.</p><p>Some queries, especially complex ones, can be resource-intensive and slow. Caching the results of these queries can significantly reduce the load on your database and improve response times for users. If a query result doesn’t change frequently (e.g., a list of popular blogs or an index of authors), caching it can drastically speed up the application.</p><p><strong><em>How to Cache Querysets in Django:</em></strong></p><p><strong>cache_page</strong> is a simple caching decorator provided by Django. It caches the entire output of a view for a specified time period. This is useful when the result of a view doesn’t change often (e.g., a list of blogs or blog details).</p><pre>from django.views.generic import ListView<br>from django.utils.decorators import method_decorator<br>from django.views.decorators.cache import cache_page<br>from .models import Blog<br><br>class BlogListView(ListView):<br>    model = Blog<br>    template_name = &#39;blog_list.html&#39;<br>    context_object_name = &#39;blogs&#39;<br>    paginate_by = 10<br><br>    @method_decorator(cache_page(60 * 15))  # Cache this view for 15 minutes<br>    def get(self, request, *args, **kwargs):<br>        return super().get(request, *args, **kwargs)</pre><p>In this example, the <strong>BlogListView </strong>will be cached for 15 minutes. Each time the same view is accessed within that time, Django will serve the cached version instead of running the query again.</p><p>If you want more control over caching specific querysets, you can use Django’s <strong>cache.set()</strong> method to store and retrieve cached data manually.</p><pre>from django.core.cache import cache<br>from django.http import JsonResponse<br>from django.views import View<br>from .models import Blog<br><br>class CachedBlogsView(View):<br>    def get(self, request, *args, **kwargs):<br>        blogs = cache.get(&#39;blogs_list&#39;)<br><br>        if not blogs:<br>            blogs = list(Blog.objects.all())<br>            cache.set(&#39;blogs_list&#39;, blogs, timeout=60*15)<br><br>        return JsonResponse({&#39;blogs&#39;: blogs})</pre><p>We first try to retrieve the list of blogs from the cache using <strong>cache.get(‘blogs_list’)</strong>. If the data is not in the cache, we fetch it from the database and cache it using <strong>cache.set()</strong>. The timeout argument specifies how long the cache will live before it expires (15 minutes in this case).</p><p>We cache the blogs and their related authors after fetching them using prefetch_related. This approach ensures that both the database queries and repeated query fetching are optimized.</p><p>By caching querysets and using techniques like <strong>cache_page, cache.set()</strong>, and <strong>prefetch_related</strong>, you can significantly improve the performance of your Django application, reduce the number of database queries, and provide a faster user experience.</p><h3>Using Raw SQL in Django</h3><p>While Django’s ORM is powerful and simplifies database operations, there are situations where it may not be sufficient, especially when dealing with complex queries or when performance is critical. In such cases, you may want to write raw SQL queries to take advantage of database-specific features, optimize query performance, or execute complex SQL operations that the ORM cannot easily handle.</p><p>Django provides several ways to execute raw SQL queries, including <strong>raw()</strong> and <strong>connection.cursor()</strong>. Here’s an overview of these methods and how to use them.</p><p>You may consider using raw SQL in the following situations:</p><ol><li><strong>Complex Queries</strong>: When you need to write a query with complex joins, subqueries, or specific SQL functions that are difficult or inefficient to express in the ORM.</li><li><strong>Performance</strong>: When you need fine-grained control over your query for performance reasons, such as optimizing queries with indexing, advanced joins, or aggregate functions.</li><li><strong>Database-Specific Features</strong>: When you need to use specific database functions or features (like stored procedures or advanced filtering) that aren’t easily accessible through the ORM.</li></ol><p>Django provides a <strong>raw()</strong> method for executing raw SQL queries on models. It allows you to execute a custom SQL query and retrieve model instances based on the results.</p><p>Here’s an example of how to use <strong>raw()</strong>:</p><pre>from myapp.models import Blog<br><br>def get_blogs_by_author(author_name):<br>    query = &quot;SELECT * FROM myapp_blog WHERE author = %s&quot;<br>    blogs = Blog.objects.raw(query, [author_name])<br>    return blogs</pre><p>In this example, the raw() method executes the SQL query and returns a list of Blog model instances, similar to what you would expect from the ORM. The query uses %s to parameterize the input, which helps prevent SQL injection and safely inserts the author_name value into the query.</p><p>Sometimes, you may need even more control over your SQL queries, such as when you want to execute a query without returning model instances or when you need to execute non-select queries (e.g., <strong>UPDATE</strong>, <strong>INSERT</strong>, <strong>DELETE</strong>).</p><p>Django’s <strong>connection.cursor()</strong> allows you to execute raw SQL and fetch the results using a cursor.</p><p>Here’s how you can use <strong>connection.cursor()</strong> to run custom SQL queries:</p><pre>from django.db import connection<br><br>def my_custom_sql(value):<br>    with connection.cursor() as cursor:<br>        cursor.execute(&quot;SELECT * FROM my_table WHERE some_field = %s&quot;, [value])<br>        return cursor.fetchall()</pre><p>In this example, we use connection.cursor() to create a cursor and execute a custom SQL query. The cursor.execute() method runs the SQL query, with the query being parameterized using %s to safely insert the value into the query. Finally, cursor.fetchall() retrieves all the rows returned by the query.</p><p><strong><em>Differences Between Model.objects.raw() and connection.cursor():</em></strong></p><ul><li><strong>Model.objects.raw()</strong>: This method is higher-level and returns model instances based on the results of the query. It’s the best option when you need to fetch records and work with them as Django model instances.</li><li><strong>connection.cursor()</strong>: This method gives you more control over the query and can be used for more complex database operations. It doesn’t return model instances but rather a raw result set (tuples), making it suitable for custom queries or non-select SQL statements.</li></ul><p><strong><em>Security: Preventing SQL Injection:</em></strong></p><p>When using raw SQL, always make sure to parameterize your queries. Avoid constructing queries by concatenating strings, as this opens the door for SQL injection attacks. Instead, use parameterized queries with <strong>%s</strong> placeholders, as shown in the examples above.</p><pre># Don&#39;t do this!<br>cursor.execute(&quot;SELECT * FROM my_table WHERE some_field = &#39;&quot; + value + &quot;&#39;&quot;)</pre><p>This can be exploited by an attacker to inject malicious SQL. Always use parameterized queries instead:</p><pre># Correct way<br>cursor.execute(&quot;SELECT * FROM my_table WHERE some_field = %s&quot;, [value])</pre><h3>Performance Testing in Django</h3><p>The <strong>Django Debug Toolbar</strong> is one of the most commonly used tools for performance testing and debugging in Django applications. It is a powerful tool that provides insights into various aspects of your Django app, including database queries, request/response times, cache usage, and more.</p><p>Installation: To install the Django Debug Toolbar, you need to install it via pip and add it to your installed apps in <strong>settings.py</strong>.</p><pre>pip install django-debug-toolbar</pre><p>Add it to <strong>INSTALLED_APPS</strong> and <strong>middleware</strong>:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;debug_toolbar&#39;,<br>]<br><br>MIDDLEWARE = [<br>    ...<br>    &#39;debug_toolbar.middleware.DebugToolbarMiddleware&#39;,<br>]</pre><p>Add it to your URLconf (<strong>urls.py</strong>):</p><pre>from django.conf import settings<br>from django.urls import path, include<br><br>if settings.DEBUG:<br>    import debug_toolbar<br>    urlpatterns = [<br>        path(&#39;__debug__/&#39;, include(debug_toolbar.urls)),<br>        ...<br>    ]</pre><p>Once installed, you can view the debug toolbar in your browser whenever you access your Django app in development mode (i.e., DEBUG=True).</p><p><strong><em>Key Features:</em></strong></p><ul><li><strong>SQL Queries Panel</strong>: This panel shows the queries executed during the request, their execution time, and any potential issues like the N+1 query problem.</li><li><strong>Cache Panel</strong>: Displays cache hits and misses, helping you evaluate if your caching strategy is working efficiently.</li><li><strong>Template Panel</strong>: Shows the time taken to render templates.</li><li><strong>Request Panel</strong>: Displays detailed request/response cycle information, including request duration and headers.</li><li><strong>Usage for Query Optimization</strong>: The SQL panel in Django Debug Toolbar is especially useful for identifying inefficient queries. You can see the exact SQL queries executed and check if they are optimized or if any unnecessary queries (such as N+1 queries) are being run.</li></ul><p>To further optimize database performance and debugging, we can create a custom <strong>database debug decorator</strong>. This decorator helps to track the number of SQL queries executed during a specific function and outputs the queries for easier analysis.</p><pre>def database_debug(func):<br>    &quot;&quot;&quot;<br>    Description: Return function_name, query_count and queries.<br>    Usage:<br>        @database_debug<br>        def query():<br>            ...<br>            return queryset<br><br>        ## Result<br>        function_name: query<br>        query_count: 1<br>        queries: SQL Query<br>    &quot;&quot;&quot;<br>    def inner_func(*args, **kwargs):<br>        if DEBUG:<br>            reset_queries()<br>            results = func(*args, **kwargs)<br>            query_info = connection.queries<br>            print(f&#39;function_name: {func.__name__}&#39;)<br>            print(f&#39;query_count: {len(query_info)}&#39;)<br>            queries = [f&#39;{query[&quot;sql&quot;]}\n&#39; for query in query_info]<br>            print(f&#39;queries: \n{&quot;&quot;.join(queries)}&#39;)<br>            return results<br>        else:<br>            return func(*args, **kwargs)<br>    return inner_func</pre><p>Let’s test the database_debug decorator with different types of database queries.</p><pre>  @database_debug<br>  def regular_query():<br>      blog_qs = Blog.objects.all()<br>      return [blog_obj.author.name for blog_obj in blog_qs]<br>  <br>    ## Result<br>    function_name: regular_query<br>    query_count: 4<br>    queries:<br>    SELECT &quot;blog_blog&quot;.&quot;id&quot;, &quot;blog_blog&quot;.&quot;title&quot;,<br>    &quot;blog_blog&quot;.&quot;description&quot;, &quot;blog_blog&quot;.&quot;author_id&quot;,<br>    &quot;blog_blog&quot;.&quot;created_at&quot;, &quot;blog_blog&quot;.&quot;updated_at&quot; FROM<br>    &quot;blog_blog&quot;<br>    SELECT &quot;author_author&quot;.&quot;id&quot;, &quot;author_author&quot;.&quot;name&quot;,<br>    &quot;author_author&quot;.&quot;email&quot; FROM<br>    &quot;author_author&quot; WHERE &quot;author_author&quot;.&quot;id&quot; = 1 LIMIT 21<br>    SELECT &quot;author_author&quot;.&quot;id&quot;, &quot;author_author&quot;.&quot;name&quot;,<br>    &quot;author_author&quot;.&quot;email&quot; FROM<br>    &quot;author_author&quot; WHERE &quot;author_author&quot;.&quot;id&quot; = 2 LIMIT 21<br>    SELECT &quot;author_author&quot;.&quot;id&quot;, &quot;author_author&quot;.&quot;name&quot;,<br>    &quot;author_author&quot;.&quot;email&quot; FROM<br>    &quot;author_author&quot; WHERE &quot;author_author&quot;.&quot;id&quot; = 2 LIMIT 21<br><br><br> @database_debug<br> def select_related_query():<br>     blog_qs = Blog.objects.select_related(&#39;author&#39;).all()<br>     return [blog_obj.author.name for blog_obj in blog_qs]<br><br>    ## Result<br>    function_name: select_related_query<br>    query_count: 1<br>    queries:<br>    SELECT &quot;blog_blog&quot;.&quot;id&quot;, &quot;blog_blog&quot;.&quot;title&quot;,<br>    &quot;blog_blog&quot;.&quot;description&quot;, &quot;blog_blog&quot;.&quot;author_id&quot;,<br>    &quot;blog_blog&quot;.&quot;created_at&quot;, &quot;blog_blog&quot;.&quot;updated_at&quot;,<br>    &quot;author_author&quot;.&quot;id&quot;, &quot;author_author&quot;.&quot;name&quot;,<br>    &quot;author_author&quot;.&quot;email&quot; FROM<br>    &quot;blog_blog&quot; INNER JOIN &quot;author_author&quot; ON<br>    (&quot;blog_blog&quot;.&quot;author_id&quot; = &quot;author_author&quot;.&quot;id&quot;)<br><br><br>@database_debug<br>def prefetch_related_query():<br>    blog_qs = Blog.objects.prefetch_related(&#39;author&#39;).all()<br>    return [blog_obj.author.name for blog_obj in blog_qs]<br><br>    ## Result<br>    function_name: prefetch_related_query<br>    query_count: 2<br>    queries:<br>    SELECT &quot;blog_blog&quot;.&quot;id&quot;, &quot;blog_blog&quot;.&quot;title&quot;,<br>    &quot;blog_blog&quot;.&quot;description&quot;, &quot;blog_blog&quot;.&quot;author_id&quot;,<br>    &quot;blog_blog&quot;.&quot;created_at&quot;, &quot;blog_blog&quot;.&quot;updated_at&quot; FROM<br>    &quot;blog_blog&quot;<br>    SELECT &quot;author_author&quot;.&quot;id&quot;, &quot;author_author&quot;.&quot;name&quot;,<br>    &quot;author_author&quot;.&quot;email&quot; FROM<br>    &quot;author_author&quot; WHERE &quot;author_author&quot;.&quot;id&quot; IN (1, 2)</pre><h3>Conclusion</h3><p>By using these advanced optimization strategies in your Django projects, you’ll improve performance significantly. Always measure the impact and keep refining your approach.</p><p>Keep optimizing, and your Django apps will perform better and scale more efficiently.</p><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><h3>References</h3><p><a href="https://docs.djangoproject.com/en/5.1/ref/models/querysets/">https://docs.djangoproject.com/en/5.1/ref/models/querysets/</a></p><p><a href="https://docs.djangoproject.com/en/4.2/topics/db/optimization/">https://docs.djangoproject.com/en/5.1/topics/db/optimization/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb4b25877dce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/django-query-optimizations-how-to-make-your-app-faster-eb4b25877dce">Django Query Optimizations: Speed Up Your App Efficiently</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency in Go: Harnessing Goroutines and Channels for Efficient Parallelism]]></title>
            <link>https://medium.com/analytics-vidhya/concurrency-in-go-efficient-parallelism-with-goroutines-and-channels-d4f8983e3f30?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f8983e3f30</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[go-programming]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 20:22:56 GMT</pubDate>
            <atom:updated>2025-03-27T19:26:37.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkwfcv0hDDPBqK-H7h2KIg.jpeg" /></figure><p>Have you ever wondered how applications like Uber, Kubernetes, or Docker handle thousands of concurrent tasks efficiently? The answer lies in Golang’s concurrency model! Unlike traditional thread-based programming, Go leverages <strong>goroutines and channels</strong>, allowing you to build scalable and high-performance applications with ease. 🚀</p><h3>✅ Goroutines: The Foundation of Concurrency in Go</h3><p>Goroutines are the backbone of Go’s concurrency model. Unlike OS threads, goroutines are lightweight and managed by Go’s <strong>M:N scheduler</strong>, which dynamically maps <strong>M goroutines</strong> to <strong>N OS threads</strong>. To start a new goroutine, simply use the go keyword before a function call:</p><pre>func fetchData(url string) {<br>    resp, err := http.Get(url)<br>    if err != nil {<br>        log.Println(&quot;Error fetching:&quot;, url)<br>        return<br>    }<br>    defer resp.Body.Close()<br>    fmt.Println(&quot;Fetched:&quot;, url)<br>}<br><br>func main() {<br>    urls := []string{&quot;https://golang.org&quot;, &quot;https://google.com&quot;, &quot;https://github.com&quot;}<br>    <br>    for _, url := range urls {<br>        go fetchData(url) // Each API call runs in a separate goroutine<br>    }<br>    <br>    time.Sleep(2 * time.Second) // Prevent main from exiting early<br>}</pre><p>✅ <strong>Explanation:</strong></p><ul><li>This example demonstrates how goroutines can be used to <strong>fetch multiple URLs concurrently</strong>.</li><li>The fetchData function makes an HTTP request to a given URL and prints the response status.</li><li>The main function iterates over a list of URLs and <strong>spawns a separate goroutine for each request</strong>.</li><li><strong>Problem:</strong> Since the main function might exit before all goroutines complete, we add time.Sleep(2 * time.Second) as a temporary fix.</li><li><strong>Better Alternative:</strong> Instead of time.Sleep, we should use a sync.WaitGroup to wait for all goroutines to complete before the program exits.</li></ul><h3>🔄 How Go Schedules Goroutines Efficiently</h3><p>The diagram above illustrates Go’s <strong>M:N scheduler</strong>, where multiple <strong>goroutines (G1, G2, G3, etc.)</strong> are dynamically mapped to a smaller number of <strong>OS threads (T1, T2)</strong>. This allows Go to efficiently manage concurrency with low overhead. The Go runtime automatically schedules goroutines across available threads for optimal performance.</p><p>Go does not map goroutines directly to OS threads. Instead, it uses an <strong>M:N scheduler</strong>, dynamically assigning goroutines to available threads, ensuring:</p><ul><li><strong>Lower context-switching overhead</strong></li><li><strong>Efficient CPU utilization</strong></li><li><strong>Dynamic stack management</strong></li></ul><p>Go’s runtime automatically suspends and resumes goroutines when necessary to optimize performance.</p><h3>Synchronization in Go: Avoiding Data Races</h3><p>Concurrent programming introduces <strong>race conditions, deadlocks,</strong> and <strong>resource contention</strong>. Go provides several mechanisms to ensure safe synchronization.</p><h3>Using sync.WaitGroup to Wait for Goroutines</h3><p>sync.WaitGroup ensures that goroutines complete before the program exits:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;sync&quot;<br>)<br><br>// fetchData makes an HTTP request and logs the response<br>func fetchData(url string, wg *sync.WaitGroup) {<br>    defer wg.Done() // Mark this goroutine as done when function exits<br><br>    resp, err := http.Get(url)<br>    if err != nil {<br>        log.Println(&quot;Error fetching:&quot;, url, err)<br>        return<br>    }<br>    defer resp.Body.Close()<br><br>    fmt.Println(&quot;Fetched:&quot;, url)<br>}<br><br>func main() {<br>    urls := []string{&quot;https://golang.org&quot;, &quot;https://google.com&quot;, &quot;https://github.com&quot;}<br>    var wg sync.WaitGroup<br><br>    for _, url := range urls {<br>        wg.Add(1) // Increment WaitGroup counter<br>        go fetchData(url, &amp;wg)<br>    }<br><br>    wg.Wait() // Wait for all goroutines to finish before exiting<br>    fmt.Println(&quot;All requests completed&quot;)<br>}</pre><p>This updated version replaces the <strong>unreliable </strong><strong>time.Sleep(2 * time.Second)</strong> with sync.WaitGroup, which is the correct way to wait for multiple goroutines to finish before exiting.</p><h4>Key Enhancements:</h4><ol><li><strong>Using </strong><strong>sync.WaitGroup for Proper Synchronization</strong></li></ol><ul><li>wg.Add(1) is called <strong>before starting a goroutine</strong>, incrementing the counter.</li><li>Each goroutine runs wg.Done() at the end to decrement the counter.</li><li>The main function calls wg.Wait(), which <strong>blocks execution until all goroutines have completed</strong>.</li></ul><p><strong>2. Why Remove </strong><strong>time.Sleep(2 * time.Second)?</strong></p><ul><li>time.Sleep <strong>does not guarantee</strong> all requests will finish before exiting.</li><li>If some requests take longer than expected, they might be terminated before completion.</li><li>If requests finish faster than 2 seconds, the program <strong>waits unnecessarily</strong>.</li></ul><p><strong>3. Improved Scalability and Reliability</strong></p><ul><li>This approach ensures <strong>all HTTP requests complete</strong>, no matter how long they take.</li><li>It works for <strong>any number of URLs</strong> without manual sleep tuning.</li></ul><h3>sync.Mutex: Ensuring Safe Access to Shared Resources</h3><p>When multiple goroutines access the same variable, <strong>race conditions</strong> can occur. To prevent this, use <strong>sync.Mutex (mutual exclusion):</strong></p><pre>var mu sync.Mutex<br>var count int<br><br>func increment() {<br>    mu.Lock()<br>    count++<br>    mu.Unlock()<br>}</pre><p>The Lock() call ensures that only one goroutine can access count at a time.</p><h3>sync.RWMutex: Optimizing Read Operations</h3><p>If multiple goroutines need to read data but not modify it, <strong>sync.RWMutex</strong> allows multiple <strong>readers</strong> but only one <strong>writer</strong> at a time:</p><pre>var rwMu sync.RWMutex<br>var data string<br><br>func readData() {<br>    rwMu.RLock()<br>    fmt.Println(data)<br>    rwMu.RUnlock()<br>}<br><br>func writeData(newData string) {<br>    rwMu.Lock()<br>    data = newData<br>    rwMu.Unlock()<br>}</pre><h3>Channels: Go’s Message-Passing Mechanism</h3><p>Go encourages <strong>message passing over shared memory</strong>. <strong>Channels</strong> facilitate safe communication between goroutines.</p><h3>Basic Channel Usage</h3><pre>ch := make(chan string)<br><br>go func() {<br>    ch &lt;- &quot;Hello, Channels!&quot;<br>}()<br><br>fmt.Println(&lt;-ch)</pre><h3>Buffered vs. Unbuffered Channels</h3><ul><li><strong>Unbuffered channels</strong>: The sender <strong>blocks</strong> until the receiver is ready.</li><li><strong>Buffered channels</strong>: Store a fixed number of values before blocking.</li></ul><pre>ch := make(chan string, 2)<br>ch &lt;- &quot;Message 1&quot;<br>ch &lt;- &quot;Message 2&quot;<br>fmt.Println(&lt;-ch)  // &quot;Message 1&quot;</pre><h3>Handling Multiple Channels with select</h3><p>select allows waiting on multiple channels simultaneously:</p><pre>ch1 := make(chan string)<br>ch2 := make(chan string)<br><br>go func() { ch1 &lt;- &quot;Data from ch1&quot; }()<br>go func() { ch2 &lt;- &quot;Data from ch2&quot; }()<br><br>select {<br>case msg := &lt;-ch1:<br>    fmt.Println(msg)<br>case msg := &lt;-ch2:<br>    fmt.Println(msg)<br>}</pre><h3>Common Pitfalls and Performance Optimizations</h3><h3>Deadlocks</h3><p>If goroutines <strong>wait indefinitely</strong> for resources, the system may halt. Avoid deadlocks by:</p><ul><li><strong>Closing channels properly</strong> after use.</li><li><strong>Using timeouts with </strong><strong>select</strong>.</li></ul><pre>ch := make(chan string)<br><br>go func() {<br>    ch &lt;- &quot;Message&quot;<br>}()<br><br>msg := &lt;-ch // This works fine<br><br>close(ch)   // Always close channels when done</pre><p>✅ <strong>Explanation:</strong></p><ul><li>This example shows a <strong>properly handled</strong> channel operation.</li><li>A goroutine sends &quot;Message&quot; to the channel ch, and the main function receives it via &lt;-ch.</li><li><strong>Why does this work?</strong> The sender and receiver are properly synchronized.</li><li><strong>Best Practice:</strong> Always <strong>close channels</strong> when they are no longer needed to avoid <strong>goroutine leaks</strong> and potential deadlocks.</li></ul><h3>Goroutine Leaks</h3><p>Goroutines that <strong>block indefinitely</strong> cause memory leaks. Use context.WithTimeout() to prevent this:</p><pre>ctx, cancel := context.WithTimeout(context.Background(), time.Second)<br>defer cancel()<br><br>select {<br>case &lt;-ctx.Done():<br>    fmt.Println(&quot;Timeout!&quot;)<br>}</pre><h3>Performance Optimizations</h3><ul><li><strong>Use worker pools</strong> to efficiently manage large numbers of goroutines.</li><li><strong>Leverage </strong><strong>sync.Pool</strong> to reduce memory allocation overhead.</li><li><strong>Profile applications</strong> with pprof to detect bottlenecks.</li></ul><p>Profiling with pprof:</p><pre>import (<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    _ &quot;net/http/pprof&quot;<br>)<br><br>func main() {<br>    go func() {<br>        log.Println(http.ListenAndServe(&quot;localhost:6060&quot;, nil))<br>    }()<br><br>    // Your app logic...<br>}</pre><ul><li>This example shows <strong>how to enable performance profiling in a Go application</strong> using pprof.</li><li>The net/http/pprof package <strong>registers profiling handlers</strong> when imported.</li><li>The goroutine starts an HTTP server on localhost:6060, which allows profiling tools to <strong>collect runtime performance data</strong>.</li><li><strong>How to Use It?</strong> Once running, you can analyze performance by visiting <a href="http://localhost:6060/debug/pprof/">http://localhost:6060/debug/pprof/.</a></li><li>This is particularly useful for detecting <strong>CPU bottlenecks, memory leaks, or goroutine leaks</strong>.</li></ul><h3>Conclusion</h3><p>Go’s concurrency model, powered by <strong>goroutines and channels</strong>, provides a simple yet powerful approach to parallelism. By leveraging <strong>synchronization primitives</strong> and <strong>best practices</strong>, developers can build highly efficient and scalable applications.</p><p>With Go, <strong>multithreaded programming becomes intuitive and fun</strong>. Mastering these concepts will enable you to develop <strong>fast, reliable, and scalable</strong> systems effortlessly! 🚀</p><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f8983e3f30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/concurrency-in-go-efficient-parallelism-with-goroutines-and-channels-d4f8983e3f30">Mastering Concurrency in Go: Harnessing Goroutines and Channels for Efficient Parallelism</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File uploads with Amazon S3 in a Django Project]]></title>
            <link>https://medium.com/analytics-vidhya/file-uploads-with-amazon-s3-in-a-django-project-54fb989e992d?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/54fb989e992d</guid>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 09:54:12 GMT</pubDate>
            <atom:updated>2025-03-27T18:59:58.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*8j73n2I5K60kH4CuXT65qA.png" /></figure><p>In a Django project, we’re going to show an example using to allow you to upload files safely and securely to an <strong>AWS S3</strong> as external storage. Unfortunately, there are no free solutions available and my <a href="https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc"><strong>Amazon Free Tier</strong></a> has expired. Also If you want a production-ready system, you can use <a href="https://min.io/?utm_source=lyapustin"><strong>MinIO</strong></a>.</p><h3>Let’s start!</h3><p>If you want to quickly set up Django project, you can visit Django <a href="https://docs.djangoproject.com/en/2.2/intro/tutorial01/"><strong>doc</strong></a>. Firstly, we create a <strong>Product</strong> model into your models.py file and make sure to save it in your <strong>admin.py</strong> file. So you can access <strong>Product </strong>model<strong> </strong>from Django Admin page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb25a292d0af9930edccb26ba2aa67e7/href">https://medium.com/media/cb25a292d0af9930edccb26ba2aa67e7/href</a></iframe><p>This is a simple Django model that can be used to store <strong>product photo</strong>. Django admin allows file uploads using the File field on a model. Now, we are going to use UI to Django Admin page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvNlCUA7WozPhdyfvVxmsA.png" /><figcaption>Django Administration Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h00Z6nvtR-KrUgjj3yDWLA.png" /><figcaption>Product List Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AE3fLq4qp9Hqk8_gRan8hw.png" /><figcaption>Product Add Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVvBz0N9tcyOiGO5IOIIWQ.png" /><figcaption>Product List Page After Product Is Added</figcaption></figure><h3>Where was the file uploaded ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*LEkOUUJ3aPOtvtohQa7qqg.png" /></figure><p><em>Ass you can see, file is uploaded to the root directory of the app.</em></p><p>We can change <strong>MEDIA_ROOT</strong> property in the <strong>settings file</strong> of your app. The path given in <strong>MEDIA_ROOT</strong> where media files load will be stored.</p><pre>MEDIA_ROOT = os.path.join(BASE_DIR, &#39;path/to/store/my/files/&#39;) </pre><p>Now, if we upload again a file, there is a new file path created to the photo uploaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*P4XlgPJv3DeCd439r-a2qQ.png" /></figure><h3>Plan</h3><p>Amazon S3 offers a secure, reliable and scalable storage system. We can remove the <strong>MEDIA_ROOT</strong> property from the <strong>settings file. </strong>Now following the steps below for creating an S3 bucket easily by logging into your AWS account:</p><ul><li>Login AWS account.</li><li>Create bucket from S3 section of the AWS console.</li><li>Create a user with Programmatic access from IAM console and give to all of permissions for full access about S3. If user is created, access key and secret access key are generated. Then you should set them in your <strong>settings.py </strong>file like shown below:</li></ul><pre>AWS_ACCESS_KEY_ID = &#39;YOUR_ACCESS_KEY_HERE&#39;<br>AWS_SECRET_ACCESS_KEY = &#39;YOUR_SECRET_ACCESS_KEY_HERE&#39;</pre><p>Also, you can visit <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/walkthrough1.html#walkthrough1-add-users"><strong>AWS</strong> <strong>doc</strong></a><strong> </strong>for creating IAM users and a group.</p><h3>Helper Libraries</h3><p>We need to install 2 python libraries:</p><ul><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html"><strong>boto3</strong></a><strong>: </strong>We can manage AWS services from within your code.</li><li><a href="https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html"><strong>django-storages</strong></a><strong>: </strong>We use Amazon S3 functionality via <strong>django-storages. </strong>You will need to add ‘storages’ into your <strong>INSTALLED_APPS</strong> of settings file too.</li></ul><p>Now, we can run below commands in your terminal.</p><pre>$ pip install boto3<br>$ pip install django-storages</pre><p>Here are the settings you should provide:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2342502bf35e702a19bd62d3775b7195/href">https://medium.com/media/2342502bf35e702a19bd62d3775b7195/href</a></iframe><p>We made settings quickly and easily with a very simple using. You should be able to easily add it to your Django projects.</p><p>You can also visit the documents below for extra information.</p><ul><li><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html">Using buckets.</a></li><li><a href="https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html">Signing examples</a>.</li></ul><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54fb989e992d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/file-uploads-with-amazon-s3-in-a-django-project-54fb989e992d">File uploads with Amazon S3 in a Django Project</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Models: Working with M2M Intermediary Models]]></title>
            <link>https://erdimollahseyin.medium.com/django-models-working-with-m2m-intermediary-models-3919ebe3a5cf?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3919ebe3a5cf</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[admin]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 10:14:52 GMT</pubDate>
            <atom:updated>2025-03-27T19:20:32.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Many-to-Many Relationships in Django: A Guide to Intermediary Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Z7DZcXwEhOnLaL8FmVtvUw.jpeg" /></figure><p>In this article, we will learn how to use <strong>through</strong> for Django many-to-many relationship. A few times in the last month, I’ve run into the need to add some metadata to a Django many-to-many relationship.</p><p>Let’s go <strong>through</strong> an example the existing models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cziePW8-m9c3Ehcx9q1B8A.png" /><figcaption><strong>Person and Group Model</strong></figcaption></figure><p>Create a model that matches the existing <strong>through</strong> table and using <strong>Meta.db_table</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbJKSWg5LdexaxOEz5JRNw.png" /><figcaption><strong>Membership Model</strong></figcaption></figure><p>Now, we change the many-to-many relationship to use the new model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AsKISwunmOwzur7fAekSg.png" /><figcaption><strong>Group Model</strong></figcaption></figure><p>Now generate a new migration with <strong>python manage.py makemigrations</strong>. Then we will change it.</p><p><strong>The initial migration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sm41f_M4r0P8X9LuIFQJKQ.png" /><figcaption><strong>Migration File</strong></figcaption></figure><p>We just need to wrap these operations in <strong>migrations.SeparateDatabaseAndState</strong> to get the models in sync without screwing up the existing database setup. All of the changes above represent state changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWyUXO5U6mGm7wDKq9buhQ.png" /><figcaption><strong>Migration File</strong></figcaption></figure><p>Now you can add fields and create additional migrations as normal.</p><h3>Admin</h3><p>Admin should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDcPy8aQI9VienQ8wphxKQ.png" /><figcaption><strong>Person, Group and Membership Admin</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNWTBdYIIWiAV72ERkP5xw.png" /><figcaption><strong>Person Admin</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CZi7mbrOWTEHm0rO2bblA.png" /><figcaption><strong>Group Admin</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_ILl7xaeTJX4bJ4dtrphQ.png" /><figcaption><strong>Group Admin</strong></figcaption></figure><h3>Filtering on through fields</h3><p>You should be able to filter on the <strong>through</strong> table fields by using the lowercase name of the <strong>through</strong> model.</p><pre># querysets<br>Group.objects.filter(membership__invite_reason=&quot;foo&quot;)<br>&lt;QuerySet [&lt;Group: Python&gt;]&gt;<br><br>Group.objects.filter(membership__invite_reason=&quot;bar&quot;)<br>&lt;QuerySet [&lt;Group: Django&gt;]&gt;<br><br>Person.objects.filter(membership__invite_reason=&quot;foo&quot;)<br>&lt;QuerySet [&lt;Person: Erdi&gt;]&gt;<br><br>Person.objects.filter(membership__invite_reason=&quot;bar&quot;)<br>&lt;QuerySet [&lt;Person: Erdi&gt;]&gt;<br><br>Membership.objects.filter(invite_reason=&#39;foo&#39;)<br>&lt;QuerySet [&lt;Membership: Erdi Python&gt;]&gt;<br><br>Membership.objects.filter(invite_reason=&#39;bar&#39;)<br>&lt;QuerySet [&lt;Membership: Erdi Django&gt;]&gt;<br><br># related manager on instances<br>person_instance = Person.objects.first()<br>person_instance.groups.filter(membership__invite_reason=&#39;foo&#39;)<br>&lt;QuerySet [&lt;Group: Python&gt;]&gt;<br>    <br>group_instance = Group.objects.first()<br>group_instance.members.filter(membership__invite_reason=&#39;foo&#39;)<br>&lt;QuerySet [&lt;Person: Erdi&gt;]&gt;</pre><p>In this article you’ve learned how to use a <strong>through</strong> with many-to-many relationship. If you want to see more information on <strong>through</strong>, you can visit <a href="https://docs.djangoproject.com/en/3.0/topics/db/models/">this</a>.</p><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3919ebe3a5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Django RESTful API]]></title>
            <link>https://medium.com/analytics-vidhya/build-a-django-restful-api-b7f4633d01bc?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7f4633d01bc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Sun, 10 Nov 2019 08:38:01 GMT</pubDate>
            <atom:updated>2025-03-27T19:19:15.461Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a RESTful API in Django: A Step-by-Step Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_6oZAheCwiQiKHAHeJDK5w.png" /></figure><h3>Section Overview</h3><ul><li>Setup.</li><li>Create the django project and application.</li><li>Model and database.</li><li>Access to the data.</li><li>Conclusion.</li></ul><p>Together, we’re going to build the back-end for a “To Do” application. We write and deploy a RESTful API service. The APIs allow you to Create, Read, Update, and Delete (CRUD) a task. The tasks are stored in a database and we’re using the Django ORM (Object Relational Mapping) to deal with the database management.</p><h3>Section 1 — Setup</h3><p>Create a Python 3 virtual environment.</p><pre>$ mkdir todoapp<br>$ cd todoapp<br>$ python3 -m venv .venv<br>$ source .venv/bin/activate</pre><p>Install the dependencies.</p><pre>(.venv)$ pip install djangorestframework django</pre><p><a href="https://www.django-rest-framework.org/">DRF(Django REST Framework)</a> is a framework that create RESTful CRUD APIs and gives useful features.</p><h3>Section 2 — Create The Django Project And Application</h3><pre>$ django-admin startproject todo_app</pre><p>Create the app in project.</p><pre>$ cd todo_app<br>$ django-admin startapp todo</pre><p>Let’s add rest_framework and todo to the list of INSTALL_APPS in the project’s settings.py.</p><pre>todoapp/todo_app/settings.py</pre><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;todo&#39;,<br>]</pre><h3>Section 3 — Model And Database</h3><p>By default, Django uses the SQLite database management system.</p><p>todo_app/todo/models.py:</p><pre>from django.db import models</pre><pre>class Task(models.Model):<br>    STATES = ((&#39;todo&#39;, &#39;To Do&#39;), (&#39;in progress&#39;, &#39;In Progress&#39;), (&#39;done&#39;, &#39;Done&#39;))<br>    title = models.CharField(max_length=255, blank=False, unique=True)<br>    description = models.TextField()<br>    status = models.CharField(max_length=4, choices=STATES, default=&#39;todo&#39;)</pre><p>Now create the database migration script that Django uses to update the database with changes.</p><pre>python manage.py makemigrations</pre><p>Then you can apply the migration to the database.</p><pre>python manage.py migrate</pre><h3>Section 4 — Access To The Data</h3><h4>Section 4.1 — Creating a Serializer</h4><p>Serializers are used to deserialize JSON or other content types into the data structure defined in the model.</p><p>Let’s add our TaskSerializer object by creating a new file in the project todo_app/todo/serializers.py:</p><pre>from rest_framework.serializers import ModelSerializer<br>from todo.models import Task<br></pre><pre>class TaskSerializer(ModelSerializer):<br>    class Meta:<br>        model = Task<br>        fields = &#39;__all__&#39;</pre><p>We’re using the generic ModelSerializer from DRF, to automatically create a serializer with the fields that correspond to our Task model.</p><h4>Section 4.2 — Creating a View</h4><p>The ModelViewSet provides the following actions on a data model: list, retrieve, create, update, partial update, and destroy.</p><p>Let’s add our view to todo_app/todo/views.py:</p><pre>from rest_framework.viewsets import ModelViewSet</pre><pre>from .models import Task<br>from .serializers import TaskSerializer</pre><pre>class TaskViewSet(ModelViewSet):<br>    queryset = Task.objects.all()<br>    serializer_class = TaskSerializer</pre><h4>Section 4.3 — Creating a Router</h4><p>The DRF DefaultRouter takes care of mapping actions to HTTP Method and URLs. Add the following to todo_app/urls.py:</p><pre>from django.conf.urls import include, url<br>from django.contrib import admin</pre><pre>from rest_framework.routers import DefaultRouter<br>from todo.views import TaskViewSet</pre><pre>router = DefaultRouter()<br>router.register(r&#39;todo&#39;, TaskViewSet)</pre><pre>urlpatterns = [<br>    url(https://medium.com/r&#39;admin/&#39;,%20admin.site.urls),<br>    url(https://medium.com/r&#39;^api/&#39;,%20include((router.urls,%20&#39;todo&#39;))),<br>]</pre><p>We’re mapping all the router URLs to the /api endpoint. DRF takes care of mapping the URLs and HTTP methods(list, retrieve, create, update, destroy).</p><h4>Section 4.4 — Running the application</h4><pre>python manage.py runserver</pre><ul><li>Now we can access the application at the following URL: <a href="http://127.0.0.1:8000/api/">http://127.0.0.1:8000/api/</a></li><li>Listing or creating tasks, using the following URL: <a href="http://127.0.0.1:8000/api/todo">http://127.0.0.1:8000/api/todo</a></li><li>Updating/deleting an existing tasks with this URL: <a href="http://127.0.0.1:8000/api/todo/1">http://127.0.0.1:8000/api/todo/1</a></li></ul><h3>Section 5 — Conclusion</h3><p>In this article you’ve learned how to create a basic RESTful API using the Django REST Framework.</p><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f4633d01bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/build-a-django-restful-api-b7f4633d01bc">Build a Django RESTful API</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT(JSON Web Tokens) For DRF]]></title>
            <link>https://medium.com/analytics-vidhya/jwt-json-web-tokens-for-drf-e091931c2193?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e091931c2193</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 12:29:45 GMT</pubDate>
            <atom:updated>2025-03-27T19:16:09.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Authentication with JSON Web Tokens (JWT) in Django Rest Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tzVd5KDGwtqATl0FUsxT3w.jpeg" /></figure><h3>Section Overview</h3><ul><li>build django project.</li><li>define the news content model and admin.</li><li>configure news content api.</li><li>authentication and permissions.</li><li>adding JWT(JSON Web Token).</li><li>swagger docs.</li></ul><p><a href="https://jwt.io/">JSON Web Token</a> is an Token based authentication used by client/server applications where the client is a web, native, mobile or something else application using. JWT is a popular implementation of token based authentication.</p><p>In this article we’ll use it to authenticate users that JWT using with <a href="https://www.django-rest-framework.org/">Django REST Framework</a>. When the news content is created, only current logged in a user can perform read and write operations to his own news contents.</p><h3>Section 1. Build Django Project</h3><p>Firstly, install Django, Django REST Framework(DRF) and django-cors-headers (CORS).</p><pre>$ pip install django django-rest-framework django-cors-headers</pre><p>Then, create a new project folder (news_contents/).</p><pre>$ mkdir news_contents<br>$ cd news_contents</pre><p>Create venv(virtual environment) and activate it.</p><pre>$ python -m venv venv<br>$ source venv/bin/activate</pre><p>Now, build a django project (core).</p><pre>$ django-admin startproject core<br>$ cd core</pre><p>Create a newscontents app.</p><pre>$ python manage.py startapp newscontents<br>$ python manage.py migrate</pre><p>We will now configure our django project to use CORS and DRF in core/settings.py.</p><pre># Application definition</pre><pre>INSTALLED_APPS = [<br>    ....<br>    &#39;rest_framework&#39;,<br>    &#39;corsheaders&#39;,<br>    &#39;newscontents&#39;,<br>]</pre><pre>MIDDLEWARE = [<br>    ....<br>    &#39;corsheaders.middleware.CorsMiddleware&#39;,<br>]</pre><pre>CORS_ORIGIN_ALLOW_ALL = True</pre><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;:[&#39;rest_framework.permissions.AllowAny&#39;],<br>    &#39;DEFAULT_PARSER_CLASSES&#39;: [&#39;rest_framework.parsers.JSONParser&#39;],<br>}</pre><p>Let’s run the server.</p><pre>$ python manage.py runserver<br>Watching for file changes with StatReloader<br>Performing system checks...</pre><pre>System check identified no issues (0 silenced).<br>November 08, 2019 - 07:24:30<br>Django version 2.2.7, using settings &#39;core.settings&#39;<br>Starting development server at http://127.0.0.1:8000/<br>Quit the server with CONTROL-C.</pre><h3>Section 2. Define The NewsContent Model And Admin</h3><p>Create NewsContent Model in core/newscontents/models.py.</p><pre>from django.conf import settings<br>from django.contrib.auth import get_user_model<br>from django.db import models</pre><pre>USER_MODEL = get_user_model()</pre><pre>class NewsContent(models.Model):<br>    reporter = models.ForeignKey(<br>        to=USER_MODEL,<br>        on_delete=models.CASCADE,<br>        related_name=&#39;news_contents&#39;,<br>    )<br>    headline = models.CharField(max_length=255)<br>    body = models.TextField()</pre><pre>    def __str__(self):<br>        return self.headline</pre><p>Run migrations.</p><pre>$ python manage.py makemigrations<br>$ python manage.py migrate</pre><p>The admin site of NewsContentModel in core/newscontents/admin.py.</p><pre>from django.contrib import admin<br>from .models import NewsContent</pre><pre>admin.site.register(NewsContent)</pre><p>Create a supuruser.</p><pre>$ python manage.py createsuperuser<br>Username: reporter<br>Email address: reporter@example.com<br>Password: <br>Password (again):<br>Superuser created successfully.</pre><p>Let’s start the server again.</p><pre>$ python manage.py runserver<br>Watching for file changes with StatReloader<br>Performing system checks...</pre><pre>System check identified no issues (0 silenced).<br>November 08, 2019 - 07:35:23<br>Django version 2.2.7, using settings &#39;core.settings&#39;<br>Starting development server at http://127.0.0.1:8000/<br>Quit the server with CONTROL-C.</pre><h3>Section 3. Configure News Content API</h3><p>Add some urls so we can access the news content API in core/urls.py.</p><pre>....<br>from django.urls import include, path</pre><pre>urlpatterns = [<br>    ....<br>    path(&#39;api/&#39;, include(&#39;newscontents.urls&#39;)),<br>]</pre><p>Then, create a serializer for NewsContent model in newscontents/serializers.py.</p><pre>from rest_framework import serializers<br>from .models import NewsContent<br></pre><pre>class NewsContentSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        fields = (&#39;id&#39;, &#39;reporter&#39;, &#39;headline&#39;, &#39;body&#39;)<br>        model = NewsContent</pre><p>Next we’ll create the view in newscontents/views.py.</p><pre>from rest_framework import viewsets<br>from .models import NewsContent<br>from .serializers import NewsContentSerializer</pre><pre>class NewsContentViewSet(viewsets.ModelViewSet):<br>    queryset = NewsContent.objects.all()<br>    serializer_class = NewsContentSerializer</pre><p>Create the urls in newscontents/urls.py.</p><pre>from django.urls import path<br>from rest_framework.routers import SimpleRouter<br>from .views import NewsContentViewSet</pre><pre>router = SimpleRouter()<br>router.register(&#39;news-content&#39;, NewsContentViewSet, base_name=&quot;news_content&quot;)<br>urlpatterns = router.urls</pre><h3>Section 4. Authentication And Permissions</h3><p>Firstly, create a new user in the admin panel. Then, add the following line in core/urls.py.</p><pre>urlpatterns = [<br>    ....<br>    path(&#39;auth/&#39;, include(&#39;rest_framework.urls&#39;)),<br>]</pre><p>Then, run to server and we will create a new user and enter news content from admin panel.</p><pre>$ python manage.py runserver<br>Watching for file changes with StatReloader<br>Performing system checks...</pre><pre>System check identified no issues (0 silenced).<br>November 08, 2019 - 11:08:55<br>Django version 2.2.7, using settings &#39;core.settings&#39;<br>Starting development server at http://127.0.0.1:8000/<br>Quit the server with CONTROL-C.</pre><p>You can verify this by logging on and then going to <a href="http://localhost:8000/api/news-content/">http://localhost:8000/api/news-content/.</a></p><p>We have configured rest_framework with AllowAny. So, each users have access to newscontents. Now, we need to change into your core/settings.py file:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [&quot;rest_framework.permissions.IsAuthenticated&quot;,],<br>    &#39;DEFAULT_PARSER_CLASSES&#39;: [&#39;rest_framework.parsers.JSONParser&#39;],<br>}</pre><p>We need to change in newscontents/views.py for ensure a user sees only own News Contents objects and set user as reporter of a News Contents object.</p><pre>from rest_framework import permissions, viewsets<br>from rest_framework.exceptions import PermissionDenied</pre><pre>from .models import NewsContent<br>from .serializers import NewsContentSerializer</pre><pre>class IsReporter(permissions.BasePermission):<br>    def has_object_permission(self, request, view, obj):<br>        return obj.reporter == request.user</pre><pre>class NewsContentViewSet(viewsets.ModelViewSet):<br>    serializer_class = NewsContentSerializer<br>    permission_classes = (IsReporter,)</pre><pre>    # Ensure a user sees only own News Content objects.<br>    def get_queryset(self):<br>        user = self.request.user<br>        if user.is_authenticated:<br>            return NewsContent.objects.filter(reporter=user)<br>        raise PermissionDenied()</pre><pre>    # Set user as owner of a NewsContents object.<br>    def perform_create(self, serializer):<br>        serializer.save(owner=self.request.user)</pre><p>If you visit http://localhost:8000/api/news-content/, you should only see the news contents belonging to the current logged in user. So, we can remove the reporter field from the serializer in newscontents/serializers.py:</p><pre>from rest_framework import serializers<br>from .models import NewsContent</pre><pre>class NewsContentSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        fields = (&#39;id&#39;, &#39;headline&#39;, &#39;body&#39;)<br>        model = NewsContent</pre><p>We have configure for authentication and permissions. But DRF using still session authentication. Now we will use Json token authentication(JWT) .</p><h3>Section 5. Adding JWT(JSON Web Token)</h3><p>We will use a library (djangorestframework_simplejwt).</p><pre>$ pip install djangorestframework_simplejwt</pre><p>We add it to DEFAULRAUTHENTICATION_CLASSES in core/settings.py.</p><pre>REST_FRAMEWORK = {<br> &#39;DEFAULT_PERMISSION_CLASSES&#39;:[&quot;rest_framework.permissions.IsAuthenticated&quot;],<br>    &#39;DEFAULT_PARSER_CLASSES&#39;: [&#39;rest_framework.parsers.JSONParser&#39;],<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.SessionAuthentication&#39;,<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>       ],<br>}</pre><p>Add new end points for token of api and refresh of token in core/urls.py.</p><pre>from rest_framework_simplejwt.views import TokenObtainView, TokenRefreshView</pre><pre>urlpatterns = [<br>    ....<br>    path(&#39;api/token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain&#39;),<br>    # get a new token before the old expires.<br>    path(&#39;api/token/refresh/&#39;, TokenRefreshView.as_view, name=&#39;token_refresh&#39;),<br>]</pre><h3>User SIGN-UP</h3><p>We need new endpoint for users can sign up. Now create a new app for jwtauth.</p><pre>$ python manage.py startapp jwtauth</pre><p>Add app in core/settings.py.</p><pre>INSTALLED_APPS = [<br>    ....<br>    &#39;jwtauth&#39;,<br>]</pre><p>Then, we’ll create a new serializer for the User model. Add jwtauth/serializers.py.</p><pre>from django.contrib.auth import get_user_model</pre><pre>from rest_framework import serializers</pre><pre>User = get_user_model()<br></pre><pre>class UserCreateSerializer(serializers.ModelSerializer):<br>    password = serializers.CharField(<br>        write_only=True, required=True, style={&#39;input_type&#39;: &#39;password&#39;}<br>    )<br>    password2 = serializers.CharField(<br>        style={&#39;input_type&#39;: &#39;password&#39;}, write_only=True, label=&#39;Confirm password&#39;<br>    )</pre><pre>    class Meta:<br>        model = User<br>        fields = [&#39;username&#39;, &#39;email&#39;, &#39;password&#39;, &#39;password2&#39;]<br>        extra_kwargs = {&#39;password&#39;: {&#39;write_only&#39;: True}}</pre><pre>    def create(self, validated_data):<br>        username = validated_data[&#39;username&#39;]<br>        email = validated_data[&#39;email&#39;]<br>        password = validated_data[&#39;password&#39;]<br>        password2 = validated_data[&#39;password2&#39;]<br>        if (email and User.objects.filter(email=email).exclude(username=username).exists()<br>        ):<br>            raise serializers.ValidationError(<br>                {&#39;email&#39;: &#39;Email addresses must be unique.&#39;}<br>            )<br>        if password != password2:<br>            raise serializers.ValidationError({&#39;password&#39;: &#39;The two passwords differ.&#39;})<br>        user = User(username=username, email=email)<br>        user.set_password(password)<br>        user.save()<br>        return user</pre><p>Then we’ll create a new view in jwtauth/views.py.</p><pre>from django.contrib.auth import get_user_model<br>from rest_framework import permissions<br>from rest_framework import response, decorators, permissions, status<br>from rest_framework_simplejwt.tokens import RefreshToken<br>from .serializers import UserCreateSerializer</pre><pre>User = get_user_model()</pre><pre>@decorators.api_view([&#39;POST&#39;])<br>@decorators.permission_classes([permissions.AllowAny])<br>def registration(request):<br>    serializer = UserCreateSerializer(data=request.data)<br>    if not serializer.is_valid():<br>        return response.Response(serializer.errors, status.HTTP_400_BAD_REQUEST)        <br>    user = serializer.save()<br>    refresh = RefreshToken.for_user(user)<br>    res = {<br>        &#39;refresh&#39;: str(refresh),<br>        &#39;access&#39;: str(refresh.access_token),<br>    }<br>    return response.Response(res, status.HTTP_201_CREATED)</pre><p>We add the view to jwtauth/urls.py.</p><pre>from django.urls import path<br>from .views import registration</pre><pre>urlpatterns = [<br>    path(&#39;register/&#39;, registration, name=&#39;register&#39;)<br>]</pre><p>Next, include the jwtauth urls in core/urls.py.</p><pre>urlpatterns = [<br>    ....<br>    path(&#39;api/jwtauth/&#39;, include(&#39;jwtauth.urls&#39;), name=&#39;jwtauth&#39;),<br>]</pre><h3>Section 6. Swagger Docs</h3><pre>$ pip install django-rest-swagger</pre><p>Add it to your INSTALLED_APPS list in core/settings.py.</p><pre>INSTALLED_APPS = [<br>    &#39;rest_framework_swagger&#39;,<br>    ....<br>]</pre><pre>REST_FRAMEWORK = {<br>    ....<br> &#39;DEFAULT_SCHEMA_CLASS&#39;:&#39;rest_framework.schemas.coreapi.AutoSchema&#39;,<br>}</pre><p>Add following code core/urls.py.</p><pre>from django.contrib import admin<br>from django.urls import path, include<br>from rest_framework_swagger.views import get_swagger_view</pre><pre>schema_view = get_swagger_view(title=&quot;News Contents API&quot;)</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;api/&#39;, include(&#39;newscontents.urls&#39;)),<br>    path(&#39;auth/&#39;, include(&#39;rest_framework.urls&#39;)),<br>    path(&#39;api/jwtauth/&#39;, include(&#39;jwtauth.urls&#39;), name=&#39;jwtauth&#39;),<br>    path(&#39;api/docs/&#39;, schema_view),<br>]</pre><p>Then put the token and refresh enpoints in jwtauth/urls.py.</p><pre>from django.urls import path<br>from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView<br>from .views import registration</pre><pre>urlpatterns = [<br>    path(&quot;register/&quot;, registration, name=&quot;register&quot;),<br>    path(&quot;token/&quot;, TokenObtainPairView.as_view(), name=&quot;token_obtain_pair&quot;),<br>    path(&quot;refresh/&quot;, TokenRefreshView.as_view(), name=&quot;token_refresh&quot;),<br>]</pre><p>You can visit to http://localhost:8000/api/docs/ for the full list of APIs and the token endpoints now belong to the /jwtauth grouping.</p><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><h3>References</h3><ul><li><a href="https://www.django-rest-framework.org/">https://www.django-rest-framework.org</a></li><li><a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a></li><li><a href="https://github.com/adamchainz/django-cors-headers">https://github.com/adamchainz/django-cors-headers</a></li><li><a href="https://github.com/davesque/django-rest-framework-simplejwt">https://github.com/davesque/django-rest-framework-simplejwt</a></li><li><a href="https://django-rest-swagger.readthedocs.io/en/latest/">https://django-rest-swagger.readthedocs.io/en/latest/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e091931c2193" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/jwt-json-web-tokens-for-drf-e091931c2193">JWT(JSON Web Tokens) For DRF</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modified Preorder Tree Traversal in Django]]></title>
            <link>https://erdimollahseyin.medium.com/modified-preorder-tree-traversal-in-django-42654d49c4fc?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/42654d49c4fc</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-mptt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tree-structure]]></category>
            <category><![CDATA[hierarchical-data]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Sat, 10 Aug 2019 20:28:04 GMT</pubDate>
            <atom:updated>2025-03-27T19:13:45.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>Managing Hierarchical Data in Django with Modified Preorder Tree Traversal(MPTT)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*C5HcGhXak9VRwfhAqpjHWw.jpeg" /></figure><p>In this article, we will learn how to use django-mptt in a Django site.<br>MPTT is <a href="https://django-mptt.readthedocs.io/en/latest/">modified preorder tree traversal</a>. It’s an efficient way to store hierarchical data to your Django models. You easily determine parent-child relationships.</p><h3>Installation</h3><pre>pip install django-mptt</pre><p>You should add mptt to the INSTALLED_APPS in your settings.py file:</p><pre>INSTALLED_APPS = (<br>    &#39;django.contrib.auth&#39;,<br>    # ...<br>    &#39;mptt&#39;,<br>)</pre><p>I’ve used MPTT in one of my major projects. Consider following models for app in Django project.</p><h3>Example Models</h3><pre>from django.db import models</pre><pre>from mptt.models import MPTTModel, TreeForeignKey</pre><pre>class LocationType(models.Model):<br>  <br>  name = models.CharField(max_length=50, unique=True)<br>  ....</pre><pre>class Location(MPTTModel):  </pre><pre>  parent = TreeForeignKey(<br>       to=&#39;self&#39;,<br>       related_name=&#39;children&#39;,<br>       null=True,<br>       blank=True,<br>       on_delete=models.CASCADE,<br>  )<br>  location_type = models.ForeignKey(<br>      to=&#39;LocationType&#39;, <br>      related_name=&#39;locations&#39;,         <br>      on_delete=models.CASCADE<br>  )<br>  name = models.CharField(max_length=255)<br>  ....<br></pre><p>We firstly add imports for the MPTTModel and TreeForeignKey classes from the django-mptt library. MPTTModelprovides a base model. Then the LocationType and Locationclasses are defined. These models will also have a number of other fields: level, lft, rght, and tree_id.</p><ul><li>level: <em>The level (or “depth”) at which a node sits in the tree.</em></li><li>lft</li><li>rght</li><li>tree_id: <em>A unique identifier assigned to each root node and inherited by all its descendants.</em></li></ul><p>It also provides subclasses of MPTTModel have the following instance methods:</p><ul><li>get_ancestors(ascending=False, include_self=False)</li><li>get_children()</li><li>get_descendants(include_self=False)</li><li>get_descendant_count()</li><li>get_family()</li><li>get_next_sibling()</li><li>get_previous_sibling()</li><li><strong>get_root()</strong></li><li>get_siblings(include_self=False)</li><li><strong>insert_at(target, position=’first-child’, save=False)</strong></li><li>is_child_node()</li><li>is_leaf_node()</li><li>is_root_node()</li><li><strong>move_to(target, position=’first-child’)</strong></li></ul><p>According to me, the most important methods are <strong>move_to(), get_root(), insert_at()</strong>. These methods are particularly helpful. We change manually lft and rght values. But it’s not a good idea. I think, you can use <strong>insert_at()</strong>, if you want to update the tree with safe way. Also, we can replace manually parent and child node with <strong>move_to()</strong>.</p><p>Now create and apply the migrations to create the table in the database:</p><pre>$ python manage.py makemigrations<br>Migrations for &#39;src&#39;:<br>  src/migrations/0001_initial.py<br>    - Create model LocationType<br>    - Create model Location</pre><p>Now, We wanto to test the <strong>Tree</strong> from <strong>shell</strong>:</p><pre>$ python manage.py shell<br>Python 3.7.0 (default, Apr  1 2019, 14:21:55)</pre><pre>In[<strong>1</strong>]: <strong>from</strong> <strong>src.models import</strong> Location, LocationType</pre><pre>In[<strong>2</strong>]: continent_obj = LocationType.objects.create(name=&#39;Continent&#39;)<br>In[<strong>3</strong>]: country_obj = LocationType.objects.create( name=&#39;Country&#39;) In[<strong>4</strong>]: city_obj = LocationType.objects.create(name=&#39;City&#39;)</pre><pre>In[<strong>5</strong>]: continent_location = Location.objects.create(<br>.....:   location_type =continent_obj, <br>.....:   name=&#39;European&#39;<br>.....: )</pre><pre>In[<strong>6</strong>]: country_location = Location.objects.create(<br>.....:   parent=continent_location,<br>.....:   location_type =country_obj, <br>.....:   name=&#39;Turkey&#39;<br>.....: )</pre><pre>In[<strong>7</strong>]: city_location = Location.objects.create(<br>.....:   parent=country_location,<br>.....:   location_type =city_obj, <br>.....:   name=&#39;Istanbul&#39;<br>.....: )</pre><p><strong><em>Result for Location Type:</em></strong></p><pre>| id  | name      |<br>|:----|:----------|<br>|  1  | Continent |<br>|  2  | Country   |<br>|  3  | City      |</pre><p><strong><em>Result for Location:</em></strong></p><pre>| id  | parent_id | location_type_id |  name        |<br>|:----|:----------|:-----------------|:-------------|<br>|  1  | None      |        1         |  European    |<br>|  2  | 1         |        2         |  Turkey      |<br>|  3  | 2         |        3         |  Istanbul    |</pre><p>We want to get a listing of child locations for European:</p><pre>In[<strong>8</strong>]: continent_location.get_descendants()<br>Out[<strong>8</strong>]: &lt;TreeQuerySet [&lt;Location: Turkey&gt;, &lt;Location:Istanbul&gt;]&gt;</pre><pre>In[<strong>9</strong>]: continent_location.get_descendant_count()<br>Out[<strong>9</strong>]: 2</pre><p>We want to get a listing of parent locations for Istanbul:</p><pre>In[<strong>10</strong>]: city_location.get_ancestors(include_self=<strong>True</strong>)<br>Out[<strong>10</strong>]: &lt;TreeQuerySet [&lt;Location: European&gt;, &lt;Location: Turkey&gt;, &lt;Location: Istanbul&gt;]&gt;</pre><p>The root node of the MPTT tree (Istanbul):</p><pre>In [<strong>11</strong>]: city_location.get_root()<br>Out[<strong>11</strong>]: &lt;Location: European&gt;</pre><p>We want to see all locations on the same level as another:</p><pre>In [<strong>12</strong>]: Location.objects.create(<br>.......:   location_type=continent_obj,<br>.......:   name=&#39;Asia&#39;<br>.......: )<br>Out[<strong>12</strong>]: &lt;Location: Asia&gt;</pre><pre>In [<strong>13</strong>]: continent_location.get_siblings()<br>Out[<strong>13</strong>]: &lt;TreeQuerySet [&lt;Location: Asia&gt;]&gt;</pre><p>Level of all locations:</p><pre>In [<strong>14</strong>]: continent_location.level<br>Out[<strong>14</strong>]: 0</pre><pre>In [<strong>15</strong>]: country_location.level<br>Out[<strong>15</strong>]: 1</pre><pre>In [<strong>16</strong>]: city_location.level<br>Out[<strong>16</strong>]: 2</pre><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><h3>References</h3><ul><li><a href="https://github.com/django-mptt/django-mptt">https://github.com/django-mptt/django-mptt</a></li><li><a href="https://django-mptt.readthedocs.io/en/latest/">https://django-mptt.readthedocs.io/en/latest/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42654d49c4fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faker and Factory Boy]]></title>
            <link>https://medium.com/analytics-vidhya/factoryboy-usage-cd0398fd11d2?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0398fd11d2</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[factory-boy]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Mon, 13 May 2019 12:49:30 GMT</pubDate>
            <atom:updated>2025-03-27T19:01:19.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Models with Django using Faker and Factory Boy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*DvC1FhqEzOYSCLOzFXF0gQ.jpeg" /></figure><p>The <strong>factory_boy</strong> library(modeled after Factory Girl in Rails) the generation of data for tests. In Django, data for tests was called fixtures, loaded from files in the code.</p><p>We can install this library:</p><pre>$ pipenv install factory_boy</pre><p>Then I will create a structure like this inside my app:</p><pre>$ core/<br>  ----tests/<br>  ---------/__init__.py<br>  ---------factories/<br>  ------------------/__init__.py<br>  ------------------/company.py<br>  ---------/test_models/<br>  --------------------/__init__.py<br>  --------------------/test_company.py</pre><p>The <strong>factories folder</strong> contains the factory company that will create the company object in the testing phase. While the <strong>test_company.py</strong> file contains the test code for the <strong>company</strong>.</p><h3>Using Factories</h3><ul><li>create an object through the ORM.</li><li>use the <strong>Meta class</strong> to tell your factory which model to use.</li></ul><p>We will create company factory in `<strong>core/factories/company.py</strong>`:</p><pre>import factory</pre><pre>class CompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>       | id  | name      |<br>       |:----|:----------|<br>       |  1  | X Company |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.Company&#39;<br>        django_get_or_create = (&#39;name&#39;,)</pre><pre>    name = &#39;company name&#39;</pre><p>The factory’s Meta has <strong>django_get_or_create</strong> set, which means the factory will call the Django built-in `<strong>Company.objects.get_or_create</strong>` method.</p><p>Now, just calling `<strong>CompanyFactory.build()</strong>` will generate a filled <strong>company</strong> instance:</p><pre># Build a Company instance and override company<br>&gt;&gt;&gt; company_obj = CompanyFactory.build(name=&#39;X Company&#39;)<br>&gt;&gt;&gt; company_obj.name<br>    &quot;X Company&quot;</pre><p>Now creating and having a company on your database is simple as writing `<strong>CompanyFactory.create()</strong>`:</p><pre># Returns a saved Company instance<br>&gt;&gt;&gt; company = Company.create(name=&#39;X Company&#39;)</pre><pre># or</pre><pre># Same as CompanyFactory.create()<br>&gt;&gt;&gt; company = CompanyFactory(name=&#39;X Company&#39;)</pre><p>You can access the object within your tests:</p><pre>from test_factories import CompanyFactory<br>company = CompanyFactory()</pre><p>You can pass a different value in when you use the factory:</p><pre>company = CompanyFactory(name=&#39;Y Company&#39;)</pre><p>Our company instance will have a name of `<strong>Y Company</strong>` instead of `<strong>company name</strong>`.</p><p>We want to create more objects:</p><pre>&gt;&gt;&gt; companies = Company.create_batch(3, name=factory.Sequence(lambda n: &#39;Name {0}&#39;.format(n)))</pre><pre>&gt;&gt;&gt; len(companies)<br>    3</pre><pre>&gt;&gt;&gt; [company.name for company in companies]<br>    [&quot;Name 1&quot;, &quot;Name 2&quot;, &quot;Name 3&quot;]</pre><p>Factories are classes used to generate data for specific models. These are called by the tests.</p><p>This is our updated `<strong>main/tests/test_models/company.py</strong>`:</p><pre>from django.test import TestCase</pre><pre>from ..factories import CompanyFactory</pre><pre>class CompanyModelsTestCase(TestCase):<br>    <a href="http://twitter.com/classmethod">@classmethod</a><br>    def setUpTestData(cls):<br>        cls.Company = CompanyFactory._meta.model</pre><pre>    def test_crud_company(self):        <br>        # create<br>        company = CompanyFactory(name=&#39;X Company&#39;)</pre><pre>        # read<br>        self.assertEqual(company.name, &#39;X Company&#39;)<br>        self.assertEqual(company.pk, company.id)<br>        self.assertQuerysetEqual(<br>            self.Company.objects.all(),                 <br>            [&#39;&lt;Company: X Company&gt;&#39;]<br>        )</pre><pre>        # update<br>        company.name = &#39;Y Company&#39;<br>        company.save()<br>        self.assertQuerysetEqual(<br>            self.Company.objects.all(),  <br>            [&#39;&lt;Company: Y Company&gt;&#39;]<br>        )</pre><h3>Features of Factory Boy:</h3><ul><li>Use a `<strong>Sequence</strong>` object using a lambda function to dynamically create unique field values. For example;</li></ul><pre>name = factory.Sequence(lambda n: ‘company_%d’ % n)`</pre><ul><li>Use a `<strong>LazyAttribute</strong>` object to return a value for a defined field. For example;</li></ul><pre>slug = factory.LazyAttribute(lambda o: o.name)</pre><ul><li>Subfactories</li><li>Many-to-many relationship</li></ul><h4>Sequences</h4><p>If you want to create multiple instances of a given object and unique attribute,<br>you can add <strong>factory.Sequence</strong>.</p><pre>import factory</pre><pre>class CompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>       | id  | name      |<br>       |:----|:----------|<br>       |  1  | X Company |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.Company&#39;<br>        django_get_or_create = (&#39;name&#39;,)</pre><pre>    name = factory.Sequence(lambda n: &#39;Company %d&#39; % n)</pre><p>When this factory is called, create a unique company each time, <strong>n</strong> is incerementing automatically.</p><h4>Lazy Attributes</h4><p>`<strong>o</strong>` is the instance being constructed within the factory.<br>You can use string formatting, with some attribute.</p><pre>import factory</pre><pre>class CompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>       | id  | name      |<br>       |:----|:----------|<br>       |  1  | X Company |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.Company&#39;<br>        django_get_or_create = (&#39;name&#39;,)</pre><pre>    name = factory.Sequence(lambda n: &#39;Company %d&#39; % n)<br>    slug = factory.LazyAttribute(lambda o: o.name)</pre><h4>SubFactories</h4><p>I needed to define a factory for testing in a Django app. The models had a one-to-many relationship, e.g. <strong>company</strong> has many <strong>contracted</strong> <strong>companies</strong>. Factory Boy allows you to use sub-factories within your factories. <strong>SubFactory</strong> is used for FK fields.</p><pre>import factory</pre><pre>class CompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>       | id  | name      |<br>       |:----|:----------|<br>       |  1  | X Company |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.Company&#39;<br>        django_get_or_create = (&#39;name&#39;,)</pre><pre>    name = factory.Sequence(lambda n: &#39;Company %d&#39; % n)<br>    slug = factory.LazyAttribute(lambda o: o.name)</pre><pre>class ContractedCompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>        | id  | start_date      | end_date      | company |<br>        |:----|:--------------------------------|:--------|<br>        |  1  | 2019-05-13      | 2020-05-13     | 1      |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.ContractedCompany&#39;</pre><pre>    start_date = parse_date(&#39;2019-05-13&#39;)<br>    end_date = parse_date(&#39;2020-05-13&#39;)<br>    company = factory.SubFactory(CompanyFactory)</pre><p>I will create a contracted company with in my tests:</p><pre>contracted_company = ContractedCompanyFactory()</pre><h4>Many-to-many relationship</h4><p>We use base building block for this feature is the post_generation:</p><pre>class CompanyFactory(factory.DjangoModelFactory):<br>    &quot;&quot;&quot;<br>       | id  | name      |<br>       |:----|:----------|<br>       |  1  | X Company |<br>    &quot;&quot;&quot;</pre><pre>    class Meta:<br>        model = &#39;core.Company&#39;<br>        django_get_or_create = (&#39;name&#39;,)</pre><pre>    name = factory.Sequence(lambda n: &#39;Company %d&#39; % n)<br>    slug = factory.LazyAttribute(lambda o: o.name)</pre><pre>    @factory.post_generation<br>    def phones(self, create, extracted):<br>        if not create:<br>            return<br>        if extracted:<br>            for phone in extracted:<br>                self.phones.add(phone)</pre><pre>    <a href="http://twitter.com/factory">@</a>factory.post_generation<br>    def emails(self, create, extracted):<br>        if not create:<br>            return<br>        if extracted:<br>            for email in extracted:<br>                self.emails.add(email)</pre><pre>    <a href="http://twitter.com/factory">@</a>factory.post_generation<br>    def addresses(self, create, extracted):<br>        if not create:<br>            return<br>        if extracted:<br>            for address in extracted:<br>                self.addresses.add(address)</pre><p>When calling CompanyFactory() or CompanyFactory.build(), <strong>no</strong> <strong>phones </strong>or<strong> no</strong> <strong>emails</strong> or <strong>no</strong> <strong>addresses</strong> binding will be created. But when CompanyFactory.create(phones=(phone1, phone2, phone3), .....) is called, the phones declaration will add passed in phones to the set of phones for the company.</p><h3>Example: Fakes And Factories</h3><ul><li><strong>faker</strong>: generate fake data</li><li><strong>factory_boy</strong>: create factories of our models</li></ul><p>In our Django apps, we have the MTV(Model Template View) structure. Firstly, we have to create models for tests. If you want to generate random strings or generate unique instances of our models, we need to use them.</p><h3>Start Django Project</h3><p>We have created a simple Django app. Look in our models.py file:</p><pre><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> django.db <strong>import</strong> models</pre><pre>User <strong>=</strong> get_user_model()<br></pre><pre><strong>class</strong> <strong>NewsContent</strong>(models<strong>.</strong>Model):<br>    headline <strong>=</strong> models<strong>.</strong>CharField(max_length<strong>=</strong>255)<br>    body <strong>=</strong> models<strong>.</strong>TextField()<br>    author <strong>=</strong> models<strong>.</strong>ForeignKey(<br>        to<strong>=</strong>User,<br>        on_delete<strong>=</strong>models<strong>.</strong>CASCADE,<br>        related_name<strong>=</strong>&#39;contents_by_author&#39;<br>    )</pre><pre>    <strong>def</strong> <strong>__str__</strong>(self):<br>        <strong>return</strong> self<strong>.</strong>headline</pre><h3>Functionality</h3><p>Now, we have some custom logic in our system. That’s right! It’s time for adding some tests. Look in our <strong>views.py</strong> file:</p><pre><strong>from</strong> django.http <strong>import</strong> HttpResponseNotAllowed<br><strong>from</strong> django.shortcuts <strong>import</strong> render<br><br><strong>from</strong> .models <strong>import</strong> NewsContent<br><br><br><strong>def</strong> <strong>news_content_list</strong>(request, author_id):<br>    <strong>if</strong> request<strong>.</strong>method <strong>==</strong> &#39;GET&#39;:<br>        object_list <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>filter(<br>            author__id<strong>=</strong>author_id<br>        )<br>        <strong>return</strong> render(request, &#39;news_content_list.html&#39;, locals())<br>    <strong>return</strong> HttpResponseNotAllowed([&#39;GET&#39;])</pre><p>Look in our <strong>news_content_list.html</strong> file:</p><pre>{% for news_content in object_list %}<br>   &lt;ul&gt;<br>        &lt;li&gt;<br>            {{ news_content.headline }}, {{ news_content.author }}<br>        &lt;/li&gt;<br>        &lt;li&gt;{{ news_content.body }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>{% endfor %}</pre><h3>Plan Our Testing</h3><p>Let’s add our first test. If we have 5 news contents by a single author we have to assure that the view lists them all.</p><pre><em># in tests/test_views.py</em><br><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> django.test <strong>import</strong> TestCase<br><strong>from</strong> django.urls <strong>import</strong> reverse<br><br><strong>from</strong> .models <strong>import</strong> NewsContent<br><br>User <strong>=</strong> get_user_model()<br><br><br><strong>class</strong> <strong>NewsContentListViewTests</strong>(TestCase):<br>    <strong>def</strong> <strong>setUp</strong>(self):<br>        self<strong>.</strong>author <strong>=</strong> User<strong>.</strong>objects<strong>.</strong>create_user(<br>            &#39;john&#39;, &#39;lennon@thebeatles.com&#39;<br>        )<br>        self<strong>.</strong>news_content <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Real Madrid frustrated by Athletic&#39;,<br>            body<strong>=</strong>&#39;Real Madrid hit the woodwork three times&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        self.url <strong>=</strong> reverse(<br>            &#39;news:news_content_list&#39;, <br>             args<strong>=</strong>(self<strong>.</strong>author<strong>.</strong>id,)<br>        )<br><br>    <strong>def</strong> <strong>test_with_several_news_content_by_one_user</strong>(self):<br>        news1 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Test Title 1&#39;,<br>            body<strong>=</strong>&#39;Test Body 1&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news2 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Test Title 2&#39;,<br>            body<strong>=</strong>&#39;Test Body 2&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news3 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Test Title 3&#39;,<br>            body<strong>=</strong>&#39;Test Body 3&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news4 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Test Title 4&#39;,<br>            body<strong>=</strong>&#39;Test Body 4&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news5 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>&#39;Test Title 5&#39;,<br>            body<strong>=</strong>&#39;Test Body 5&#39;,<br>            author<strong>=</strong>self<strong>.</strong>author<br>        ) <br><br>        response <strong>=</strong> self<strong>.</strong>client<strong>.</strong>get(self<strong>.</strong>url)<br><br>        self<strong>.</strong>assertEqual(200, response<strong>.</strong>status_code)<br>        self<strong>.</strong>assertContains(response, news1<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news2<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news3<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news4<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news5<strong>.</strong>headline)</pre><h3>Let’s start refactoring</h3><p>First, why using <strong>faker</strong> that is a <strong>Python</strong> package that generates fake data for you. How our tests are <strong>changing</strong> to look like:</p><pre><em># in tests/test_views.py</em><br><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> django.test <strong>import</strong> TestCase<br><strong>from</strong> django.urls <strong>import</strong> reverse<br><strong>from</strong> faker <strong>import</strong> Factory<br><br><strong>from</strong> .models <strong>import</strong> NewsContent<br><br>User <strong>=</strong> get_user_model()<br><br><br>faker <strong>=</strong> Factory<strong>.</strong>create()<br><br><br><strong>class</strong> <strong>NewsContentListViewTests</strong>(TestCase):<br>    <strong>def</strong> <strong>setUp</strong>(self):<br>        self<strong>.</strong>author <strong>=</strong> User<strong>.</strong>objects<strong>.</strong>create_user(<br>                          faker<strong>.</strong>name(), <br>                          faker<strong>.</strong>email()<br>                      )<br>        self<strong>.</strong>news_content <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(),<br>            body<strong>=</strong>faker<strong>.</strong>text(),<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        self.url <strong>=</strong> reverse(<br>            &#39;news:news_content_list&#39;, <br>             args<strong>=</strong>(self<strong>.</strong>author<strong>.</strong>id,)<br>        )<br><br>    <strong>def</strong> <strong>test_with_several_news_content_by_one_user</strong>(self):<br>        news1 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(),<br>            body<strong>=</strong>faker<strong>.</strong>text(),<br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news2 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(), <br>            body<strong>=</strong>faker<strong>.</strong>text(), <br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news3 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(), <br>            body<strong>=</strong>faker<strong>.</strong>text(), <br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news4 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(), <br>            body<strong>=</strong>faker<strong>.</strong>text(), <br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br>        news5 <strong>=</strong> NewsContent<strong>.</strong>objects<strong>.</strong>create(<br>            headline<strong>=</strong>faker<strong>.</strong>word(), <br>            body<strong>=</strong>faker<strong>.</strong>text(), <br>            author<strong>=</strong>self<strong>.</strong>author<br>        )<br><br>        response <strong>=</strong> self<strong>.</strong>client<strong>.</strong>get(self<strong>.</strong>url)<br><br>        self<strong>.</strong>assertEqual(200, response<strong>.</strong>status_code)<br>        self<strong>.</strong>assertContains(response, news1<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news2<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news3<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news4<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news5<strong>.</strong>headline)</pre><p>If you want to learn more useful methods about faker, you can visit <a href="https://faker.readthedocs.io/en/master/providers.html">it</a>. We have the same test functionality as before. Faker is randomly <strong>generating values</strong>. Now create some factories. Factories are <strong>Python</strong> classes and write to your database as Django models do.</p><pre>Model<strong>.</strong>objects<strong>.</strong>create()</pre><pre><strong>or</strong></pre><pre>ModelFactory()</pre><p>Let’s create factories for our models:</p><pre><strong>import</strong> factory<br><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> faker <strong>import</strong> Factory</pre><pre><strong>from</strong> my_news.news.models <strong>import</strong> NewsContent</pre><pre>User <strong>=</strong> get_user_model()</pre><pre>faker <strong>=</strong> Factory<strong>.</strong>create()<br></pre><pre><strong>class</strong> <strong>UserFactory</strong>(factory<strong>.</strong>DjangoModelFactory):<br>    <strong>class</strong> <strong>Meta</strong>:<br>        model <strong>=</strong> User</pre><pre>    name <strong>=</strong> faker<strong>.</strong>name()<br>    email <strong>=</strong> faker<strong>.</strong>email()<br></pre><pre><strong>class</strong> <strong>NewsContentFactory</strong>(factory<strong>.</strong>DjangoModelFactory):<br>    <strong>class</strong> <strong>Meta</strong>:<br>        model <strong>=</strong> NewsContent</pre><pre>    headline <strong>=</strong> faker<strong>.</strong>word()<br>    body <strong>=</strong> faker<strong>.</strong>text()<br>    author <strong>=</strong> factory<strong>.</strong>SubFactory(UserFactory)</pre><ul><li><strong>class Meta</strong>: define the model of your factory</li><li><strong>faker</strong> : generate random values</li><li>factory.SubFactory(NewsContentFactory) == models.ForeignKey(NewsContent)</li></ul><pre><em># in tests/test_views.py</em><br><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> django.test <strong>import</strong> TestCase<br><strong>from</strong> django.urls <strong>import</strong> reverse<br><strong>from</strong> faker <strong>import</strong> Factory<br><br><strong>from</strong> .factories <strong>import</strong> NewsContentFactory, UserFactory<br><strong>from</strong> .models <strong>import</strong> NewsContent<br><br>User <strong>=</strong> get_user_model()<br><br><br>faker <strong>=</strong> Factory<strong>.</strong>create()<br><br><br><strong>class</strong> <strong>NewsContentListViewTests</strong>(TestCase):<br>    <strong>def</strong> <strong>setUp</strong>(self):<br>        self<strong>.</strong>author <strong>=</strong> UserFactory()<br>        self<strong>.</strong>news_content <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        self.url <strong>=</strong> reverse(<br>            &#39;news:news_content_list&#39;, <br>             args<strong>=</strong>(self<strong>.</strong>author<strong>.</strong>id,)<br>        )<br><br>    <strong>def</strong> <strong>test_with_several_news_content_by_one_user</strong>(self):<br>        news1 <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        news2 <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        news3 <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        news4 <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        news5 <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br><br>        response <strong>=</strong> self<strong>.</strong>client<strong>.</strong>get(self<strong>.</strong>url)<br><br>        self<strong>.</strong>assertEqual(200, response<strong>.</strong>status_code)<br>        self<strong>.</strong>assertContains(response, news1<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news2<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news3<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news4<strong>.</strong>headline)<br>        self<strong>.</strong>assertContains(response, news5<strong>.</strong>headline)</pre><h3>DRY(Don’t Repeat Yourself) — Factories</h3><p>Factories are behaving like objects from the ORM.</p><ul><li><strong>create batch</strong>: create a batch of objects without repeating our code.</li></ul><pre><em># in tests/test_views.py</em><br><strong>from</strong> django.contrib.auth <strong>import</strong> get_user_model<br><strong>from</strong> django.test <strong>import</strong> TestCase<br><strong>from</strong> django.urls <strong>import</strong> reverse<br><strong>from</strong> faker <strong>import</strong> Factory<br><br><strong>from</strong> .factories <strong>import</strong> NewsContentFactory, UserFactory<br><strong>from</strong> .models <strong>import</strong> NewsContent<br><br>User <strong>=</strong> get_user_model()<br><br><br>faker <strong>=</strong> Factory<strong>.</strong>create()<br><br><br><strong>class</strong> <strong>NewsContentListViewTests</strong>(TestCase):<br>    <strong>def</strong> <strong>setUp</strong>(self):<br>        self<strong>.</strong>author <strong>=</strong> UserFactory()<br>        self<strong>.</strong>news_content <strong>=</strong> NewsContentFactory(author<strong>=</strong>self<strong>.</strong>author)<br>        self.url <strong>=</strong> reverse(<br>            &#39;news:news_content_list&#39;, <br>             args<strong>=</strong>(self<strong>.</strong>author<strong>.</strong>id,)<br>        )<br><br>    <strong>def</strong> <strong>test_with_several_news_content_by_one_user</strong>(self):<br>        news_contents <strong>=</strong> NewsContentFactory<strong>.</strong>create_batch(<br>                             5, <br>                             author<strong>=</strong>self<strong>.</strong>author<br>                        )<br><br>        response <strong>=</strong> self<strong>.</strong>client<strong>.</strong>get(self<strong>.</strong>url)<br>        self<strong>.</strong>assertEqual(200, response<strong>.</strong>status_code)<br>        <strong>for</strong> news_content <strong>in</strong> news_contents:<br>            self<strong>.</strong>assertContains(response, news_content<strong>.</strong>headline)</pre><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><h3>Conclusion</h3><p>In this article, we learned how to use faker and factories. They are very helpful for model tests. If you want to see more information on `<strong>factory_boy</strong>`, you can visit <a href="https://factoryboy.readthedocs.io/en/latest/index.html">this</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0398fd11d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/factoryboy-usage-cd0398fd11d2">Faker and Factory Boy</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Django Sitemap]]></title>
            <link>https://medium.com/analytics-vidhya/django-sitemap-8f4ca0538fa?source=rss-6c8dafd882a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4ca0538fa</guid>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Erdi Mollahüseyinoğlu]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 11:11:11 GMT</pubDate>
            <atom:updated>2025-03-27T19:02:04.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lOwTzxyKFRoUXYHsAgg7w.jpeg" /></figure><p>Sitemap is a file with an xml extension that contains the pages of the content we have published on our site. Today, the site map has become one of the most important SEO criteria to be found on every site.</p><p>We want to start by creating a new project.</p><pre>$ django-admin startproject django_sitemap<br>$ cd django_sitemap/</pre><p>We now want to create a new app and I will call it my app.</p><pre>$ ./manage.py startapp myapp</pre><p>We can add myapp to our install apps.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;myapp&#39;,<br>]</pre><p>django_sitemap/urls.py:</p><pre>from django.contrib import admin<br>from django.urls import path, include<br>urlpatterns = [<br>    path(&#39;&#39;, include(&#39;myapp.urls&#39;)),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>]</pre><p>myapp/urls.py:</p><pre>from django.urls import path<br>from myapp.views import about<br>urlpatterns = [<br>    path(&#39;about/&#39;, about, name=&#39;about&#39;)<br>]</pre><p>myapp/views.py:</p><pre>from django.http import HttpResponse<br>def about(request):<br>    return HttpResponse(&#39;about page&#39;)</pre><p>There’s a package called Django contrib sitemaps and start creating our sitemap.</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;myapp&#39;,<br>    &#39;django.contrib.sitemaps&#39;,<br>]</pre><p>StaticViewSitemap() will be a site map for all of our static views. Every single site map has to have a function called an item and location() should return a path for every single item.</p><p>myapp/sitemaps.py:</p><pre>from django.contrib.sitemaps import Sitemap<br>from django.shortcuts import reverse<br>class StaticViewSitemap(Sitemap):<br>    def items(self):<br>        return [&#39;about&#39;]<br>    def location(self, item):<br>        return reverse(item)</pre><p>We want to import static view the site map and then we can create a new dict called site maps and we want to give it the key of static and the value of static view side map because we&#39;ll need to pass this dict in a moment.</p><p>django_sitemap/urls.py:</p><pre>from django.contrib import admin<br>from django.contrib.sitemaps.views import sitemap<br>from django.urls import include, path<br>from myapp.sitemaps import StaticViewSitemap<br>sitemaps = {<br>    &#39;static&#39;: StaticViewSitemap<br>}<br>urlpatterns = [<br>    path(&#39;&#39;, include(&#39;myapp.urls&#39;)),<br>    path(&#39;sitemap.xml&#39;, sitemap, {&#39;sitemaps&#39;: sitemaps}),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>]</pre><h4>Running the application</h4><ul><li>http://127.0.0.1:8000/sitemap.xml, we get an XML file which contains a location.</li></ul><pre>&lt;urlset xmlns=&quot;<a href="http://www.sitemaps.org/schemas/sitemap/0.9">http://www.sitemaps.org/schemas/sitemap/0.9</a>&quot;&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;<a href="http://127.0.0.1:8000/about/">http://127.0.0.1:8000/about/</a>&lt;/loc&gt;<br>    &lt;/url&gt;<br>&lt;/urlset&gt;</pre><h3>Model</h3><p>We create a snippet model.</p><pre>from django.db import models<br>from django.utils.text import slugify<br>class Snippet(models.Model):<br>    title = models.CharField(max_length=80)<br>    slug = models.SlugField(blank=True, null=True)<br>    body = models.TextField()</pre><pre>def save(self, *args, **kwargs):<br>        self.slug = slugify(self.title)<br>        super().save(*args, **kwargs)</pre><pre>def get_absolute_url(https://medium.com/self):<br>        return f&#39;/{self.slug}&#39;</pre><p>Using save() method. Because, we want to generate the slug from the title.</p><pre>$ ./manage.py makemigrations<br>$ ./manage.py migrate<br>$ ./manage.py shell<br>In [1]: from myapp.models import Snippet<br>In [2]: Snippet.objects.create(title=&#39;t1&#39;, body=&#39;&lt;h1&gt;&lt;/h1&#39;).save()<br>In [3]: Snippet.objects.create(title=&#39;t2&#39;, body=&#39;&lt;h2&gt;&lt;/h2&#39;).save()</pre><p>Now, we want to create a real path and our detail views and this one is going to take a a slug.</p><p>myapp/urls.py:</p><pre>from django.urls import path<br>from myapp.views import about, snippet_detail<br>urlpatterns = [<br>    path(&#39;&lt;slug:slug&gt;/&#39;, snippet_detail),<br>    path(&#39;about/&#39;, about, name=&#39;about&#39;),<br>]</pre><p>myapp/views.py:</p><pre>from django.http import HttpResponse<br>from django.shortcuts import get_object_or_404<br>from .models import Snippet</pre><pre>def about(request):<br>    return HttpResponse(&#39;about page&#39;)</pre><pre>def snippet_detail(request, slug):<br>    snippet = get_object_or_404(Snippet, slug=slug)<br>    return HttpResponse(f&#39;the detailview for slug of {slug}&#39;)</pre><h4>Running the application</h4><ul><li>http://127.0.0.1:8000/h2/, the detailview for slug of h2.</li></ul><p>django_sitemap/urls.py:</p><pre>from django.contrib import admin<br>from django.contrib.sitemaps.views import sitemap<br>from django.urls import include, path<br>from myapp.sitemaps import SnippetSitemap, StaticViewSitemap</pre><pre>sitemaps = {&#39;static&#39;: StaticViewSitemap, &#39;snippet&#39;: SnippetSitemap}</pre><pre>urlpatterns = [<br>    path(&#39;&#39;, include(&#39;myapp.urls&#39;)),<br>    path(&#39;sitemap.xml&#39;, sitemap, {&#39;sitemaps&#39;: sitemaps}),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>]</pre><p>myapp/sitemaps.py:</p><pre>from django.contrib.sitemaps import Sitemap<br>from django.shortcuts import reverse<br>from .models import Snippet</pre><pre>class StaticViewSitemap(Sitemap):<br>    def items(self):<br>        return [&#39;about&#39;]</pre><pre>def location(self, item):<br>        return reverse(item)</pre><pre>class SnippetSitemap(Sitemap):<br>    def items(self):<br>        return Snippet.objects.all()</pre><h4>Running the application</h4><ul><li>http://127.0.0.1:8000/sitemap.xml, we get an XML file which contains a location.</li></ul><pre>&lt;urlset xmlns=&quot;<a href="http://www.sitemaps.org/schemas/sitemap/0.9">http://www.sitemaps.org/schemas/sitemap/0.9</a>&quot;&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;<a href="http://127.0.0.1:8000/about/">http://127.0.0.1:8000/about/</a>&lt;/loc&gt;<br>    &lt;/url&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;<a href="http://127.0.0.1:8000/h1">http://127.0.0.1:8000/h1</a>&lt;/loc&gt;<br>    &lt;/url&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;<a href="http://127.0.0.1:8000/h2">http://127.0.0.1:8000/h2</a>&lt;/loc&gt;<br>    &lt;/url&gt;<br>    &lt;url&gt;<br>        &lt;loc&gt;<a href="http://127.0.0.1:8000/h3">http://127.0.0.1:8000/h3</a>&lt;/loc&gt;<br>    &lt;/url&gt;<br>&lt;/urlset&gt;</pre><p>Connect with me on, <a href="https://github.com/erdimollahuseyin">GitHub</a> and <a href="https://www.linkedin.com/in/erdi-mollahuseyinoglu/">LinkedIn</a>.</p><h3>Conclusion</h3><p>If you look in the <a href="https://docs.djangoproject.com/en/2.1/ref/contrib/sitemaps/">django site maps documentation</a>. You will find other properties which can use on the site map to tell search engines more about it. In this article you’ve learned how to create a site map.The source code of the application is available on <a href="https://github.com/erdimollahuseyin/django-site-map">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4ca0538fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/django-sitemap-8f4ca0538fa">How to create a Django Sitemap</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>