<?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 Kalpit Jain on Medium]]></title>
        <description><![CDATA[Stories by Kalpit Jain on Medium]]></description>
        <link>https://medium.com/@TheKalpit?source=rss-dc046f2bf80b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VHzPZGs08FCz2dORpaFiaQ.png</url>
            <title>Stories by Kalpit Jain on Medium</title>
            <link>https://medium.com/@TheKalpit?source=rss-dc046f2bf80b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:50:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TheKalpit/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[Stop Using useState() for Form Data]]></title>
            <link>https://medium.com/@TheKalpit/stop-using-usestate-for-form-data-ce5cc9a4ce93?source=rss-dc046f2bf80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5cc9a4ce93</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kalpit Jain]]></dc:creator>
            <pubDate>Thu, 02 May 2024 11:29:59 GMT</pubDate>
            <atom:updated>2024-05-02T19:44:14.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cCRMdoEv0EbMRwy6" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my 8 years of experience working with React, I’ve seen more people use &lt;form/&gt; with useState() than I expected to. I’m here to tell you that you can build input fields without the need of any manual effort for state management.</p><p>I’m not proposing any new JS library or React hack — quite the opposite, actually. Let the browser and HTML do the job.</p><p>If you’re new to React and still grasping the concepts, here’s a quick definition of useState(): It’s a React Hook that lets you add a state variable to a component. Most importantly, whenever the state of a component changes, the component will re-render.</p><h4>The Problem</h4><p>Let’s take a minimal login form component as an example, with just a username and password field.</p><pre>function Login() {<br>  const [formData, setFormData] = useState({<br>    username: &#39;&#39;,<br>    password: &#39;&#39;,<br>  });<br><br>  const onSubmit = (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br>    submitFormDataToServer(formData);<br>  };<br><br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Username&quot;<br>        value={formData.username}<br>        onChange={(e) =&gt;<br>          setFormData(previousData =&gt; ({<br>            ...previousData,<br>            username: e.currentTarget.value,<br>          }))<br>        }<br>      /&gt;<br>      &lt;input<br>        type=&quot;password&quot;<br>        placeholder=&quot;Password&quot;<br>        value={formData.password}<br>        onChange={(e) =&gt; <br>          setFormData(previousData =&gt; ({<br>            ...previousData,<br>            password: e.currentTarget.value,<br>          }))<br>        }<br>      /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;<br>        Login<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>If you’re using any kind of state management (including Redux/useReducer()) to store the input field values, then the component will re-render after any change in the field values.</p><p>For instance, suppose the length of your username is 10 characters and length of your password is 6 characters. First, that’s a weak password. Second, the component will re-render at least 16 times while you type the username and password.</p><p>In this specific example, you’re unlikely to notice any significant performance issue, or encounter any critical bugs — but we’re talking about best practices here. If any expensive processing was happening during component render time, you’d definitely notice some issues.</p><h4>If Not This, Then What is State?</h4><p>Before we dive into the solution, let’s first understand what should be considered as “state”. To understand this, look no further than the official React documentation:</p><blockquote>- Does it <strong>remain unchanged</strong> over time? If so, it isn’t state.<br>- Is it <strong>passed in from a parent</strong> via props? If so, it isn’t state.<br>- <strong>Can you compute it</strong> based on existing state or props in your component? If so, it <em>definitely</em> isn’t state!</blockquote><blockquote>What’s left is probably state.</blockquote><p>I know if you answer these questions literally, then my previous example seems fine. Let me tweak the last question slightly:</p><p><em>Can you compute it based on </em><strong><em>existing data</em></strong><em> in your component?</em></p><p>This statement above will lead us to an alternate and (IMO) better solution. We already have the input field values in the DOM and we just need them for sending in the API request — so if we just get the values from DOM in onSubmit() function, we can do away with any state management on our part.</p><p>I don’t want to use document.getElementBy… APIs, it can introduce more problems than it solves.</p><h4>The Solution</h4><p>Let the browser and DOM do the job. If you ever worked on a web app in pre-React era, you probably know what I mean.</p><p>The browser is already maintaining the input field values internally, that’s why you’re able to see it in the UI! Enter, FormData.</p><p>Here’s the alternate solution:</p><pre>function Login() {<br>  const onSubmit = (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br>    const formData = new FormData(e.currentTarget);<br>    submitFormDataToServer(formData);<br>  };<br><br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Username&quot;<br>        name=&quot;username&quot;<br>      /&gt;<br>      &lt;input<br>        type=&quot;password&quot;<br>        placeholder=&quot;Password&quot;<br>        name=&quot;password&quot;<br>      /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;<br>        Login<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>Notice onSubmit() function: new FormData(e.currentTarget). This will get the HTML FormData, i.e. your username and password, and if the authentication API supports it then you can even send it directly in the payload without any further processing.</p><p>If you do need to get the individual values, then you can use formData.get(&quot;username&quot;) or formData.get(&quot;password&quot;) to get the user entered data. You can read more about the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData">FormData API on the MDN docs</a>.</p><p>Is this the only solution? What if you need direct access to the input field for some reason?</p><p>I won’t go into more detail as this post is already too long. Just to guide you in the right direction — look into useRef(). You can create a reference to the input field, and then execute any available APIs for the field — including field.value, field.checked, etc.</p><p>You’ll still get all the benefits of not using useState(), i.e. no unnecessary re-renders while getting direct access to the input fields.</p><h4>Exceptions and Conclusion</h4><p>Let’s be real — you will likely get into scenarios where using state management may make sense. Just answer the 3 questions above and if using useState() makes your life, and most importantly your users’ life simple, then by all means — use state (pun intended).</p><p>One such example is showing validation errors. Although even in this case the UX can be improved by leveraging ValidityState, but that’s another topic for another day.</p><p>Can you think of any scenario when using state management for input fields makes more sense than FormData or useRef()? Let me know in the comments below.</p><p>If you have an exciting project and need a skilled, experienced engineer to bring it to life, I’m here to help. I have delivered high-quality products that have taken my clients’ business growth to the next level. I’d like to hear more about your project — <a href="https://thekalpit.com/?utm_source=medium&amp;utm_medium=blogpost&amp;utm_content=stopusestate">get in touch</a> to start the next phase of your journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5cc9a4ce93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Basics For Non-Technical Founders and Product Managers]]></title>
            <link>https://medium.com/crowdbotics/api-basics-for-non-technical-founders-and-product-managers-10f34ff19b9?source=rss-dc046f2bf80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/10f34ff19b9</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[non-technical]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Kalpit Jain]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 18:39:13 GMT</pubDate>
            <atom:updated>2019-06-13T11:24:36.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>RESTful API Basics For Non-Technical Founders and Product Managers</h3><h4>From your website to your WiFi enabled Microwave (to your own product, maybe) almost everything uses some kind of API… but how exactly does a RESTful API work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dK6F2drv8KNQKQWSUYQ5Kw.gif" /></figure><p><em>Before you continue reading, do consider that this post is written for </em><a href="https://www.crowdbotics.com/build/non-technical/?utm_campaign=v1&amp;utm_source=blog-post&amp;utm_medium=Medium&amp;utm_content=non-technical"><em>non-technical founders and product managers</em></a><em>. I’ll focus mainly on RESTful APIs in this post. I will oversimplify some concepts, and go into others in more detail.</em></p><p>With that in mind, let’s first understand why you need to know about APIs.</p><p>If you’re a product manager, founder, or have any other role which makes you responsible for product design, you must understand some basic technical concepts to make sound decisions. This will also help you make sure your team is following the right standards while building APIs.</p><h4>What is API?</h4><p>API stands for Application Programming Interface.</p><p>An API enables a web enabled application to fetch data from a server. The app communicates with the server via the API to let the server know what data it needs and in what form. The server then sends the requested data back to app via the API.</p><p>As you can make out from this (simplified) explanation, and API is used when two different applications need a common medium for communication.</p><h4>Diving Deeper…</h4><p>Simply put, an API is a way to communicate with a component without bothering with its internal functionality. An API usually expects input in a specified format and responds in a specified format as well.</p><p>The best analogy I’ve come across is that an API is similar to a restaurant. When you enter a restaurant, you’re given a menu. You select an item from it and tell the waiter to get it for you from the kitchen. You’re not aware about what happens in the kitchen, but the waiter delivers your the food on your table.</p><p>In this example, you are the web enabled application, your order is an API call, the waiter is the API itself, the kitchen is the application you are communicating with, the menu is the API documentation. You are not allowed to enter the kitchen, and the waiter can only deliver what the kitchen provides.</p><p>A washing machine (or any machine, for that matter) is an other way to think about APIs. A lot is going on inside the machine itself, but you don’t need to bother with it. The manufacturer has provided you with some buttons to control what you’re allowed to. The buttons are the <em>interface </em>through which you interact with the <em>application.</em></p><h4>RESTful APIs</h4><p>Let’s shift gears a bit, and focus on RESTful APIs.</p><p>If you’re building a mobile app, a decoupled web app, or something which requires communication with a central server, chances are that you need to have an API backend. Usually products with a presence on multiple platforms develop APIs to have a common backend that will deliver predictable results across platforms. Most products use RESTful APIs for this purpose.</p><p>RESTful, or simply referred as REST APIs, use HTTP requests to GET, PUT, POST, or DELETE data. There are actually no firm rules for using these simple commands, but there are best practices for each :</p><p>Here are some examples of what you can do with REST API requests:</p><ol><li>GET — /products to return list of products.</li><li>GET — /products/1 to return all data of a product (identified by 1).</li><li>POST — /products to create a new product.</li><li>PATCH — /products/1 to update partial data of a product (identified by 1).</li><li>PUT — /products/1 to update all data of a product (identified by 1).</li><li>DELETE — /products/1 to delete the product (identified by 1).</li></ol><p>There are best practices for API response as well. I won’t dive deep into it, but to give you an idea let’s take a couple of examples. Continuing the above endpoints, “list of products” API will return list of data of each product. The data in this API is usually minimal, as sending all data of each product will increase response size unnecessarily. Apart from that,</p><ol><li>GET method is usually used to read data only.</li><li>POST, PATCH, and PUT method is used to update/create data.</li><li>DELETE method is used to delete data.</li><li>GET method usually returns 200 HTTP response code.</li><li>POST method usually returns 201 HTTP response code.</li></ol><p>There are a lot more technical things I’m tempted to mention here, but as I mentioned earlier I’m keeping this post easily understandable for <a href="https://www.crowdbotics.com/build/non-technical/?utm_campaign=v1&amp;utm_source=blog-post&amp;utm_medium=Medium&amp;utm_content=non-technical">non-technical individuals</a>.</p><p>Let’s jump straight to things you should consider while developing APIs.</p><h4>API Security Considerations</h4><p>I mentioned earlier that making system open for public is a security hazard, even with credentials. What makes APIs secure? For starters, the public can only access and manipulate data which is allowed by APIs. Apart from that you can follow the following basic principles.</p><p><strong>Always use SSL (HTTPS)</strong>: Your users will be transferring data over network, and you can’t control their network security. What you can control is security of your application itself. Make sure your APIs are only accessible over HTTPS only.</p><p><strong>Rate Limiting</strong>: Always have a reasonable limit for accessing APIs from one user over a fixed period of time. For example, you may set a limit of 60 API calls per user per minute to avoid abuse.</p><p><strong>Authentication</strong>: There’s no one shot solution for authentication, but always use the most secure way to authenticate users over an API call, and make sure it supports a mechanism to logout user from server if needed.</p><p><strong>Permissions</strong>: Double check API permissions. Without proper permission handling one user might be able to access or update another user’s data, or in some cases get super admin permissions!</p><p><strong>Avoid Storing Sensitive Data on Client End</strong>: This is important, obvious, and one of the most common security hazard found in apps. Avoid storing sensitive data like API tokens, passwords, etc. on client side as in some cases it is very easy to get access and leak sensitive data. In case you do need to store such data, make sure you follow best practices for that particular platform or encrypt it if possible.</p><h4>Some Important Points to Consider</h4><p><strong>API Documentation</strong>: If you’re working with a team or developing APIs for public use, always create a documentation for developers who will be working on the APIs. Even when you’re singing solo, documentation can come handy more often than you anticipate.</p><p>Some major API frameworks, like Django REST Framework, provide a way to generate documentation from code automatically.</p><p><strong>Updates &amp; Backward Compatibility</strong>: Here’s the thing about API based apps: you don’t have much control over what user has already downloaded. This is especially true in the case of mobile apps, as user might be using a version older than you’re currently working on.</p><p>Keep this scenario in mind, and ask users nicely to regularly update their version of app. You may use API versioning for major or breaking changes. Don’t ignore older APIs. Test them too when working on something new.</p><p><strong>Prefer JSON</strong>: JSON APIs offer less overhead and wider support as compared to XML. Always prefer JSON based APIs, unless your use-case requires otherwise.</p><h4>Next Steps</h4><p>I hope by now you have some idea about APIs and how they work. I do not claim to have included everything you need to know about APIs in this post.</p><p>If you’re comfortable with what you’ve read so far, I’d recommend you to dive into some API development. This will really give you a much better understanding of how APIs really work.</p><p>Try <a href="https://blog.crowdbotics.com/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework/">How to write an API in 3 lines of code with Django REST framework</a> as a starting point.</p><h4><a href="https://www.crowdbotics.com/build/non-technical/?utm_campaign=v1&amp;utm_source=blog-post&amp;utm_medium=Medium&amp;utm_content=non-technical">Crowdbotics helps non-technical people turn ideas and specs into working software products</a></h4><p>If you have a project where you need additional developer resources, drop us a line. Crowbotics can help you estimate build time for given product or feature, and provide specialized developers as you need them. (<a href="https://app.crowdbotics.com/dashboard/?utm_campaign=v1&amp;utm_source=blog-post&amp;utm_medium=Medium&amp;utm_content=non-technical">We also support technical teams too! Learn more here, or try our app builder.</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10f34ff19b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crowdbotics/api-basics-for-non-technical-founders-and-product-managers-10f34ff19b9">API Basics For Non-Technical Founders and Product Managers</a> was originally published in <a href="https://medium.com/crowdbotics">Crowdbotics</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 Use Dynamic Subdomains In Django]]></title>
            <link>https://medium.com/crowdbotics/how-to-use-dynamic-subdomains-in-django-dc1cb2cac00b?source=rss-dc046f2bf80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc1cb2cac00b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Kalpit Jain]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 16:53:09 GMT</pubDate>
            <atom:updated>2019-06-12T11:28:21.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Handle Multiple (and Dynamic) Domains/Subdomains with Single Django App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzfY0Wi4AWgRaDE8p5UajA.png" /></figure><p>If you use a single Django app for <a href="https://blog.crowdbotics.com/how-to-add-a-navigation-menu-in-django-admin/">admin panel </a>— API back-end, user facing front-end, etc. — you probably use URL schemes like example.com/admin for the admin panel and example.com/api for the API back-end, or something similar.</p><p>You should really consider serving each entity on a separate domain or subdomain. Why? Because…</p><p>a) Having all entities on a single domain is a security issue.</p><pre><em>&quot;Splitting the interfaces over two hostnames—or indeed two port numbers  or protocols (HTTP/HTTPS)—would give you two different JavaScript  origins. This prevents any cross-site-scripting (XSS) attacks that are  accessible on one site from automatically infecting into the other site...&quot; - Answer by bobince on </em><a href="https://security.stackexchange.com/a/55443"><em>StackExchange</em></a></pre><p>b) Makes it easier to implement separate authentication backend, essentially keeping users with admin access away from those without admin access.</p><p>c) Makes use of dynamic domain/subdomains possible.</p><p>d) Makes it possible to serve each domain/subdomain from a different server. For example, you can point <a href="http://www.domain.com/">www.example.com</a> to a high performance server for general users, and admin.example.com to a cheaper one as it’s usually used by a handful of users.</p><p>e) It looks neat! ¯\_(ツ)_/¯</p><p><strong>We’ll learn two things by the end of this tutorial:</strong></p><ol><li>How to serve admin panel, API back-end, and user-facing front-end on different subdomains.</li><li>How to serve a single Django app on multiple (and dynamic) domains or subdomains.</li></ol><h4>Prerequisites</h4><ol><li>At least some experience with Django development.</li><li>A Django app with some URLs configured for at least two of: admin panel, APIs, or user-facing front-end.</li><li>Subdomains or domains configured in virtual hosts.</li></ol><p><em>NB: I’ve used Django v2.1, django-hosts v3.0, and Django REST Framework v3.8 for this tutorial.</em></p><h4>How to Serve Admin Panel, API, and Front-end on Different Sub-domains</h4><p>In this section we’ll configure our Django app to serve admin panel on admin.example.com, APIs on api.example.com, and user-facing front-end on <a href="http://www.domain.com./">www.example.com.</a></p><p>To make our task easier we’ll be using an amazing library by jazzband, <a href="https://github.com/jazzband/django-hosts">django-hosts</a>. Once you’ve installed django-hosts (pip install django-hosts), follow the steps below to configure it.</p><ol><li>Add django_hosts to INSTALLED_APPS in settings.py.</li><li>Add django_hosts.middleware.HostsRequestMiddleware at the <strong>beginning</strong> of MIDDLEWARE or MIDDLEWARE_CLASSES in settings.py.</li><li>Add django_hosts.middleware.HostsResponseMiddleware at the <strong>end</strong> of MIDDLEWARE or MIDDLEWARE_CLASSES in settings.py.</li><li>Create a file hosts.py in your app. Leave it blank for now, we’ll add content in it later.</li><li>Add ROOT_HOSTCONF setting in settings.py to declare path to hosts.py file you just created in previous step. eg. ROOT_HOSTCONF = &#39;myapp.hosts&#39;</li></ol><p>Next, we need to add required content in hosts.py file. Until now, you were probably putting all URL configurations in a single urls.py file. To serve each entity on different subdomains or domains, we need to create separate files similar to urls.py for each set of routes.</p><p>For example, I’ll be creating 3 files. Namely, urls.py for admin panel URL configurations, frontend_urls.py for user-facing front-end, and api_urls.py for API back-end.</p><p>The structure of each file will be similar, only difference is that urls.py will only contain paths to admin panel routes, api_urls.py will contain paths to only API URLs, and so on. Let’s quickly do that. Your files will look similar to the following:</p><pre># api_urls.py</pre><pre><strong>from </strong>django.urls <strong>import </strong>path, include</pre><pre>urlpatterns = [<br>    path(<strong>&#39;&#39;</strong>, include(<strong>&#39;polls.api.urls&#39;</strong>)),<br>]</pre><pre># frontend_urls.py</pre><pre><strong>from </strong>django.urls <strong>import </strong>path, include</pre><pre>urlpatterns = [<br>    path(<strong>&#39;&#39;</strong>, include(<strong>&#39;polls.urls&#39;</strong>)),<br>]</pre><pre># urls.py</pre><pre><strong>from </strong>django.contrib <strong>import </strong>admin<br><strong>from </strong>django.urls <strong>import </strong>path</pre><pre>urlpatterns = [<br>    path(<strong>&#39;&#39;</strong>, admin.site.urls),<br>]</pre><p>Once this is done, let’s quickly configure hosts.py to serve each set of URLs on separate subdomains.</p><pre><strong>from </strong>django.conf <strong>import </strong>settings<br><strong>from </strong>django_hosts <strong>import </strong>patterns, host</pre><pre>host_patterns = patterns(<br>    &#39;&#39;,<br>    host(r&#39;www&#39;, &#39;subdomains_tutorial.frontend_urls&#39;, name=&#39;www&#39;),<br>    host(r&#39;admin&#39;, settings.ROOT_URLCONF, name=&#39;admin&#39;),<br>    host(r&#39;api&#39;, &#39;subdomains_tutorial.api_urls&#39;, name=&#39;api&#39;),<br>)</pre><p>You might also need to define DEFAULT_HOST in settings.py.</p><p>That’s it! Now you will be able to access each subdomain, and each of them will do its job only. Neat, right?</p><p>You should also consider adding django_hosts.templatetags.hosts_override to TEMPLATES[&#39;OPTIONS&#39;][&#39;builtins&#39;] in settings.py to override default url template tag with template tag bundled with django-hosts to handle subdomains.</p><p>I’ve created a sample project with subdomains support. It’s available on GitHub: <a href="https://github.com/TheKalpit/Django-Subdomains-Tutorial">https://github.com/TheKalpit/Django-Subdomains-Tutorial</a></p><p>What if your requirements are more complex than what django-hosts provide? Don’t worry. I’ve got you covered.</p><h3>How to Serve a Single Django App on Multiple (and Dynamic) Domains/Subdomains</h3><p>In one of my previous projects, the client wanted to develop an app in Django that could also be sold as a white-labelled service.</p><p>From a development point of view, this requires a single Django app which can run on multiple, dynamically created, domains or subdomains. It should also be able to filter content and handle permissions based on the domain from which it is accessed.</p><p>Unfortunately, django-hosts can’t be used as it required hardcoded configuration, and it only supports subdomains. So, I created a custom solution.</p><p>Let’s start with a fresh Django app, and create an app named domains using the command python manage.py startapp domains. Don’t forget to add it in INSTALLED_APPS in settings.py. Create a model in this app’s models.py file as below.</p><pre><strong>from </strong>django.db <strong>import </strong>models</pre><pre><strong>class </strong>Domain(models.Model):<br>    domain = models.CharField(max_length=128, unique=<strong>True</strong>)<br>    name = models.CharField(max_length=128)</pre><pre>    <strong>def </strong>__str__(self):<br>        <strong>return </strong>self.domain</pre><p>We’ll be using this model to create domains dynamically. You can simply create a domain example.com in admin panel and a new website will be functional on example.com using the existing codebase and database.</p><p>Of course, you will need to configure the domain in virtual hosts. The configuration for the same will vary depending upon the server software you’re using.</p><p>Now that you’ve created the Domain model, let’s add it to Django Admin quickly.</p><pre><strong>from </strong>django.contrib <strong>import </strong>admin</pre><pre><strong>from </strong>.models <strong>import </strong>Domain<br></pre><pre><strong>class </strong>DomainAdmin(admin.ModelAdmin):<br>    fields = (<strong>&#39;domain&#39;</strong>, <strong>&#39;name&#39;</strong>)<br>    ordering = (<strong>&#39;domain&#39;</strong>,)<br></pre><pre>admin.site.register(Domain, DomainAdmin)</pre><p><strong>Creating django-admin Command to Create Domain from Command Line:</strong></p><p>Since we’re binding the app to specific domains, including the default one, the app might not be accessible if there are no domains added in the database. To tackle this situation, having a django-admin command is very handy.</p><p>To do so, create a python package named management in domains app. Create a regular directory named commands inside it. In commands directory create a file createdomain.py, and add the following code in it. I’ll explain it below.</p><pre><strong>import </strong>sys</pre><pre><strong>from </strong>django.core <strong>import </strong>exceptions<br><strong>from </strong>django.core.management.base <strong>import </strong>BaseCommand, CommandError<br><strong>from </strong>django.db <strong>import </strong>DEFAULT_DB_ALIAS<br><strong>from </strong>django.utils.text <strong>import </strong>capfirst</pre><pre><strong>from </strong>domains.models <strong>import </strong>Domain<br></pre><pre><strong>class </strong>NotRunningInTTYException(Exception):<br>    <strong>pass<br></strong></pre><pre><strong>class </strong>Command(BaseCommand):<br>    help = <strong>&#39;Used to create a domain.&#39;<br>    </strong>requires_migrations_checks = <strong>True<br>    </strong>stealth_options = (<strong>&#39;stdin&#39;</strong>,)</pre><pre>    <strong>def </strong>__init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.DomainModel = Domain<br>        self.domain_field = self.DomainModel._meta.get_field(<strong>&#39;domain&#39;</strong>)<br>        self.name_field = self.DomainModel._meta.get_field(<strong>&#39;name&#39;</strong>)</pre><pre>    <strong>def </strong>add_arguments(self, parser):<br>        parser.add_argument(<br>            <strong>&#39;--%s&#39; </strong>% <strong>&#39;domain&#39;</strong>,<br>            dest=<strong>&#39;domain&#39;</strong>, default=<strong>None</strong>,<br>            help=<strong>&#39;Specifies the domain.&#39;</strong>,<br>        )<br>        parser.add_argument(<br>            <strong>&#39;--database&#39;</strong>, action=<strong>&#39;store&#39;</strong>, dest=<strong>&#39;database&#39;</strong>,<br>            default=DEFAULT_DB_ALIAS,<br>            help=<strong>&#39;Specifies the database to use. Default is &quot;default&quot;.&#39;</strong>,<br>        )<br>        parser.add_argument(<br>            <strong>&#39;--%s&#39; </strong>% <strong>&#39;name&#39;</strong>, dest=<strong>&#39;name&#39;</strong>, default=<strong>None</strong>,<br>            help=<strong>&#39;Specifies the name&#39;</strong>,<br>        )</pre><pre>    <strong>def </strong>execute(self, *args, **options):<br>        self.stdin = options.get(<strong>&#39;stdin&#39;</strong>, sys.stdin)  <em># Used for testing<br>        </em><strong>return </strong>super().execute(*args, **options)</pre><pre>    <strong>def </strong>handle(self, *args, **options):<br>        domain = options[<strong>&#39;domain&#39;</strong>]<br>        name = options[<strong>&#39;name&#39;</strong>]<br>        database = options[<strong>&#39;database&#39;</strong>]</pre><pre>        verbose_domain_field_name = self.domain_field.verbose_name<br>        verbose_name_field_name = self.name_field.verbose_name</pre><pre>        <em># Enclose this whole thing in a try/except to catch<br>        # KeyboardInterrupt and exit gracefully.<br>        </em><strong>try</strong>:</pre><pre>            <strong>if </strong>hasattr(self.stdin, <strong>&#39;isatty&#39;</strong>) <strong>and not </strong>self.stdin.isatty():<br>                <strong>raise </strong>NotRunningInTTYException(<strong>&quot;Not running in a TTY&quot;</strong>)</pre><pre>            <strong>while </strong>domain <strong>is None</strong>:<br>                input_msg = <strong>&#39;%s: &#39; </strong>% capfirst(verbose_domain_field_name)<br>                domain = self.get_input_data(self.domain_field, input_msg)<br>                <strong>if not </strong>domain:<br>                    <strong>continue<br>                if </strong>self.domain_field.unique:<br>                    <strong>try</strong>:<br>                        self.DomainModel._default_manager.db_manager(database).get_by_natural_key(domain)<br>                    <strong>except </strong>self.DomainModel.DoesNotExist:<br>                        <strong>pass<br>                    else</strong>:<br>                        self.stderr.write(<strong>&quot;Error: That %s is already in use.&quot; </strong>% verbose_domain_field_name)<br>                        domain = <strong>None</strong></pre><pre><strong>            if not </strong>domain:<br>                <strong>raise </strong>CommandError(<strong>&#39;%s cannot be blank.&#39; </strong>% capfirst(verbose_domain_field_name))</pre><pre>            <strong>while </strong>name <strong>is None</strong>:<br>                input_msg = <strong>&#39;%s: &#39; </strong>% capfirst(verbose_name_field_name)<br>                name = self.get_input_data(self.name_field, input_msg)<br>                <strong>if not </strong>name:<br>                    <strong>continue</strong></pre><pre><strong>            if not </strong>name:<br>                <strong>raise </strong>CommandError(<strong>&#39;%s cannot be blank.&#39; </strong>% capfirst(verbose_domain_field_name))</pre><pre>        <strong>except </strong>KeyboardInterrupt:<br>            self.stderr.write(<strong>&quot;\nOperation cancelled.&quot;</strong>)<br>            sys.exit(1)</pre><pre>        <strong>except </strong>NotRunningInTTYException:<br>            self.stdout.write(<br>                <strong>&quot;Domain creation skipped due to not running in a TTY. &quot;<br>            </strong>)</pre><pre>        <strong>if </strong>domain <strong>and </strong>name:<br>            domain_data = {<br>                <strong>&#39;domain&#39;</strong>: domain,<br>                <strong>&#39;name&#39;</strong>: name,<br>            }<br>            self.DomainModel(**domain_data).save()<br>            <strong>if </strong>options[<strong>&#39;verbosity&#39;</strong>] &gt;= 1:<br>                self.stdout.write(<strong>&quot;Domain created successfully.&quot;</strong>)</pre><pre>    <strong>def </strong>get_input_data(self, field, message, default=<strong>None</strong>):<br>        <em>&quot;&quot;&quot;<br>        Override this method if you want to customize data inputs or<br>        validation exceptions.<br>        &quot;&quot;&quot;<br>        </em>raw_value = input(message)<br>        <strong>if </strong>default <strong>and </strong>raw_value == <strong>&#39;&#39;</strong>:<br>            raw_value = default<br>        <strong>try</strong>:<br>            val = field.clean(raw_value, <strong>None</strong>)<br>        <strong>except </strong>exceptions.ValidationError <strong>as </strong>e:<br>            self.stderr.write(<strong>&quot;Error: %s&quot; </strong>% <strong>&#39;; &#39;</strong>.join(e.messages))<br>            val = <strong>None</strong></pre><pre><strong>        return </strong>val</pre><p>It’s simply taking user input and creating a record in Domain model. The code is similar to the one Django itself uses to create super user (i.e. createsuperuser).</p><p>You can run the following command in CLI to create a domain:</p><pre>python manage.py createdomain</pre><p><strong>Creating Middleware to Detect Current Domain:</strong></p><p>So far we’ve created a model to define domain names, and a CLI command to add records in it. We plan to isolate data on each domains. To do so, first we need to let our Django app know which domain is currently accessing the app. That’s a job for a middleware. Let’s create one.</p><p>Create a file middleware.py in domain app, with the content below:</p><pre><strong>from </strong>django.utils.deprecation <strong>import </strong>MiddlewareMixin<br></pre><pre><strong>class </strong>CurrentDomainMiddleware(MiddlewareMixin):<br>    <strong>def </strong>process_request(self, request):<br>        <strong>from </strong>.models <strong>import </strong>Domain<br>        request.domain = Domain.objects.get_current(request)</pre><p>This might not make any sense at this point, that’s because we’re actually doing the actual job of detecting domain in domains/models.py for efficiency reasons.</p><p>In domains/models.py create a custom Managerclass as below:</p><pre><strong>from </strong>django.db <strong>import </strong>models<br><strong>from </strong>django.http.request <strong>import </strong>split_domain_port</pre><pre>DOMAINS_CACHE = {}<br></pre><pre><strong>class </strong>DomainManager(models.Manager):<br>    use_in_migrations = <strong>True</strong></pre><pre><strong>    def </strong>_get_domain_by_id(self, domain_id):<br>        <strong>if </strong>domain_id <strong>not in </strong>DOMAINS_CACHE:<br>            domain = self.get(pk=domain_id)<br>            DOMAINS_CACHE[domain_id] = domain<br>        <strong>return </strong>DOMAINS_CACHE[domain_id]</pre><pre>    <strong>def </strong>_get_domain_by_request(self, request):<br>        host = request.get_host()<br>        <strong>try</strong>:<br>            <strong>if </strong>host <strong>not in </strong>DOMAINS_CACHE:<br>                DOMAINS_CACHE[host] = self.get(domain__iexact=host)<br>            <strong>return </strong>DOMAINS_CACHE[host]<br>        <strong>except </strong>Domain.DoesNotExist:<br>            domain, port = split_domain_port(host)<br>            <strong>if </strong>domain <strong>not in </strong>DOMAINS_CACHE:<br>                DOMAINS_CACHE[domain] = self.get(domain__iexact=domain)<br>            <strong>return </strong>DOMAINS_CACHE[domain]</pre><pre>    <strong>def </strong>get_current(self, request=<strong>None</strong>, domain_id=<strong>None</strong>):<br>        <strong>if </strong>domain_id:<br>            <strong>return </strong>self._get_domain_by_id(domain_id)<br>        <strong>elif </strong>request:<br>            <strong>return </strong>self._get_domain_by_request(request)</pre><pre>    <strong>def </strong>clear_cache(self):<br>        <strong>global </strong>DOMAINS_CACHE<br>        DOMAINS_CACHE = {}</pre><pre>    <strong>def </strong>get_by_natural_key(self, domain):<br>        <strong>return </strong>self.get(domain=domain)</pre><p>Next step? Use this class in Domain model.</p><pre>objects = DomainManager()</pre><p>Don’t forget to add this middleware path, domains.middleware.CurrentDomainMiddleware in my case, to MIDDLEWARE in settings.py.</p><p>We’re almost there. All we’ve done so far will give us Domain object attached to each request. You can access it by request.domain anywhere request is available. Let’s test it.</p><p><strong>Put it to Test:</strong></p><p>Create another app python manage.py startapp polls and add it to INSTALLED_APPS in settings.py. Create any models you want in this app, just add a ForeignKey or ManyToManyField in it named domain or domains respectively.</p><p>Register the model(s) in admin.py as well, but don’t keep domain or domains field editable. We’ll be assigning these fields automatically while saving the model. We’ll also be using currently active domain to filter records. This is how I’ve done it:</p><pre><em># models.py</em></pre><pre><strong>from </strong>django.db <strong>import </strong>models</pre><pre><strong>from </strong>domains.models <strong>import </strong>Domain<br></pre><pre><strong>class </strong>Poll(models.Model):<br>    content = models.CharField(max_length=256)<br>    domain = models.ForeignKey(Domain, on_delete=models.CASCADE)</pre><pre>    <strong>def </strong>__str__(self):<br>        <strong>return </strong>self.content<br></pre><pre><strong>class </strong>PollOption(models.Model):<br>    poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name=<strong>&#39;poll_options&#39;</strong>)<br>    value = models.CharField(max_length=256)</pre><pre>    <strong>def </strong>__str__(self):<br>        <strong>return </strong>self.value</pre><pre># admin.py</pre><pre><strong>from </strong>django.contrib <strong>import </strong>admin</pre><pre><strong>from </strong>polls.models <strong>import </strong>PollOption, Poll</pre><pre><strong>class </strong>PollOptionInline(admin.TabularInline):<br>    model = PollOption<br>    fields = (<strong>&#39;value&#39;</strong>,)<br>    extra = 1<br></pre><pre><strong>class </strong>PollAdmin(admin.ModelAdmin):<br>    inlines = (PollOptionInline,)<br>    fields = (<strong>&#39;content&#39;</strong>, <strong>&#39;domain&#39;</strong>,)<br>    readonly_fields = (<strong>&#39;domain&#39;</strong>,)</pre><pre>    <strong>def </strong>get_queryset(self, request):<br>        qs = Poll.objects.filter(domain=request.domain)<br>        ordering = self.get_ordering(request)<br>        <strong>if </strong>ordering:<br>            qs = qs.order_by(*ordering)<br>        <strong>return </strong>qs</pre><pre>    <strong>def </strong>save_model(self, request, obj, form, change):<br>        obj.domain = request.domain<br>        <strong>return </strong>super().save_model(request, obj, form, change)<br></pre><pre>admin.site.register(Poll, PollAdmin)</pre><p>That’s it! You may now create any many domains/subdomains as you want and each one of them will have access to only the polls created within that environment.</p><p>Checkout the GitHub project with complete code here: <a href="https://github.com/TheKalpit/Django-Dynamic-Domains-Tutorial">https://github.com/TheKalpit/Django-Dynamic-Domains-Tutorial</a></p><h4>What Else Can You Do?</h4><p>What I just created is very basic as the purpose of this tutorial was to show how multiple domains can be handled in a single Django app. You can use the above approaches to create more complex apps.</p><p>For example, you can create an app in which each super admin user have access to their own domain, and nothing else — similar to “white-labeling” requirement I mentioned above.</p><p>You can create apps with single back-end panel and multiple front-end. For example, a news website with multiple domains/subdomains for multiple categories. Such website might require having some of the news articles on a single domain, and some of them on multiple domains. Instead of creating multiple apps, all of them could be managed from a single codebase and admin panel.</p><p>You can even combine both of the solutions above to create subdomains for each entity, with support for dynamically created domains. You can use this approach to modify view permissions, authentication, accessible records, and few other things based on currently active domain. Let us know what you’d use it for in your comments below.</p><p>Was this tutorial helpful? If you found any error or difficulty following it, let me know in the comments below.</p><p>If you like this post, you might also like, <a href="https://blog.crowdbotics.com/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework/"><strong>How to write an API in 3 lines of code with Django REST framework</strong></a></p><p>Thanks to <a href="https://medium.com/u/c96e7232f511">William Wickey</a> for help editing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7kqyahThCaSx77QSjO_8A.png" /></figure><h4>Building A Web Or Mobile App?</h4><p><em>Crowdbotics is the fastest way to build, launch and scale an application.</em></p><p><em>Developer? Try out the </em><a href="https://www.crowdbotics.com/app-builder/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Crowdbotics App Builder</em></strong></a><em> to quickly scaffold and deploy apps with a variety of popular frameworks.</em></p><p><em>Busy or non-technical? Join hundreds of happy teams building software with Crowdbotics PMs and expert developers. Scope timeline and cost with Crowdbotics</em><strong><em> </em></strong><a href="https://www.crowdbotics.com/managed-app-development/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Managed App Development</em></strong></a><em> for free.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc1cb2cac00b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crowdbotics/how-to-use-dynamic-subdomains-in-django-dc1cb2cac00b">How To Use Dynamic Subdomains In Django</a> was originally published in <a href="https://medium.com/crowdbotics">Crowdbotics</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 Add A Navigation Menu In Django Admin]]></title>
            <link>https://medium.com/crowdbotics/how-to-add-a-navigation-menu-in-django-admin-770b872a9531?source=rss-dc046f2bf80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/770b872a9531</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kalpit Jain]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 18:58:34 GMT</pubDate>
            <atom:updated>2019-06-12T11:20:53.595Z</atom:updated>
            <content:encoded><![CDATA[<h4>Despite all the advantages of Django Admin, it could still use a few improvements. One such tweak is adding a navigation menu in Django Admin. This tutorial will show you how to add one.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUYLSnvBSZqPAaDkgvFyoA.png" /></figure><p><a href="https://blog.crowdbotics.com/when-to-use-django-and-when-not-to/">I’ve praised Django Admin </a>in the past. It’s one of the most useful features of Django.</p><p>Despite all the advantages of Django Admin, it could still use a few improvements. One such change is adding a navigation menu in Django Admin, which we’re “fixing” in this tutorial.</p><p>When I started working with Django Admin I found it counter-intuitive to go back to homepage every time I needed to move to another module’s page. It’s something I wasn’t used to. I’m sure you’ve felt the same way (that’s why you’re here, I’m hoping!).</p><p>As developers, we’re used to navigating from one module to another directly from the navigation menu in every Admin Panel we’ve ever used. (The same goes for the client or employer you’re developing the admin panel for.) Sooner or later, you’ll likely find yourself tinkering with Django Admin templates, trying to add links to all the modules in the menu. This can get tricky.</p><p>Since the purpose of this post is to explain the procedure to add a navigation menu, we won’t be paying much attention to the design part. I’ll be using <a href="https://getbootstrap.com/docs/4.0/components/navbar/">Bootstrap Navbar Component</a> to create the UI, but you can use any other library or create your own UI from scratch.</p><p><em>Here’s what what our navigation menu in Django Admin will look like at the end of this tutorial:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2O0aoonfpcVdBDladz_BA.png" /><figcaption>Bootstrap Navbar in default Django Admin</figcaption></figure><p>Let’s create a new Django Project first.</p><h4>Creating a Django Project</h4><p>I’m using Python 3.6 and Django 2.1, but these instructions are more or less similar for other recent versions of Python &amp; Django.</p><p>Create a new directory and execute the command below to create a python virtual environment, and activate it.</p><pre># Creates a virtual environment in subdirectory &quot;venv&quot;<br>python -m venv venv</pre><pre># Activate it<br>source venv/bin/activate  # Linux<br>venv\Scripts\activate  # Windows</pre><p>While you’re in the virtual environment, install Django.</p><pre>pip install Django  # to install the latest stable release<br>pip install Django==2.1  # to install a specific version</pre><p>Once installed, you may configure the database and other settings. Without diving deeper into the setup instructions, let’s quickly create a project and fire up the development server.</p><pre>django-admin startproject navbar  # create a Django project</pre><pre>python manage.py migrate  # run migrations</pre><pre>python manage.py createsuperuser  # create a super user</pre><pre>python manage.py runserver  # start the development server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*kpAQYdqWgombavdA8cTVVg.png" /><figcaption>Django development server started successfully</figcaption></figure><p>Now, when you navigate to <a href="http://localhost:8000/">http://127.0.0.1:8000/</a> it should show you Django’s default welcome page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mUJFeyRTrSYvHfMracO9w.png" /><figcaption>Django’s default welcome page</figcaption></figure><p>To access the admin panel, go to <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a> then login using the credentials you created with python manage.py createsuperuser command.</p><p>This is what you get out of the box. A fully functional Django Admin — without navigation menu bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgb98psS8psfAXq45-iJyA.png" /><figcaption>Default Django Admin without Navbar</figcaption></figure><h4>Add Bootstrap Dependencies</h4><p>Now that we have a functional Django Admin, let’s add a navigation menu.</p><p>We won’t be writing any Python/Django code yet. We’ll just replace Django Admin’s default header with a static bootstrap Navbar.</p><p>First create a new app. Creating a separate app has its benefits. I’ll cover that in a bit.</p><pre>python manage.py startapp my_admin</pre><p>Once done, create directories /templates/admin in my_admin app. Copy default Django Admin’s base.html and base_site.html to this directory.</p><p>In my case the default directory was found at /venv/Lib/site-packages/django/contrib/admin/templates/admin/.</p><p>We’ll be working on the newly copied files, i.e. files in /my_admin/templates/admin/.</p><p>Now, to use bootstrap Navbar, first we need to add relevant bootstrap CSS and JavaScript files. To do so, download bootstrap source files from their <a href="https://getbootstrap.com/">official website</a>. We’re downloading source files because we won’t be using all features of Bootstrap. We’ll be using SASS preprocessor to pick only the parts we need.</p><p>Extract the downloaded files to /my_admin/static/admin/</p><p>With that completed, let’s start editing some HTML.</p><p>Open /my_admin/templates/admin/base.html and add the following snippet in the &lt;head&gt; section to add bootstrap CSS. Make sure you write correct path to bootstrap.scss file.</p><pre>{% load compress %}<br>{% compress css %}<br>    &lt;link rel=”stylesheet” href=”{% static “admin/bootstrap-4.1.3/scss/bootstrap.scss” %}” type=”text/x-scss” charset=”utf-8&quot;&gt;<br>{% endcompress %}</pre><p>Since we just need the Navbar component, you can remove the imports from bootstrap.scss which are not required, otherwise it might conflict with existing Django CSS. Here’s my version of bootstrap.scss for reference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12a675ad7de10a98f63248475be5d17e/href">https://medium.com/media/12a675ad7de10a98f63248475be5d17e/href</a></iframe><p>Similarly, add the following links to bootstrap JS modules. To do so, paste the following code just before closing &lt;/body&gt; tag.</p><pre>{# bootstrap js #}</pre><pre>&lt;script src=”<a href="https://code.jquery.com/jquery-3.3.1.slim.min.js">https://code.jquery.com/jquery-3.3.1.slim.min.js</a>&quot; integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” crossorigin=”anonymous”&gt;&lt;/script&gt;<br>&lt;script src=”<a href="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js">https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js</a>&quot; integrity=”sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49&quot; crossorigin=”anonymous”&gt;&lt;/script&gt;</pre><pre>{% compress js %}<br>    &lt;script src=”{% static ‘admin/bootstrap-4.1.3/js/dist/util.js’ %}” type=”text/javascript” charset=”utf-8&quot;&gt;&lt;/script&gt;<br>    &lt;script src=”{% static ‘admin/bootstrap-4.1.3/js/dist/dropdown.js’ %}” type=”text/javascript” charset=”utf-8&quot;&gt;&lt;/script&gt;<br>    &lt;script src=”{% static ‘admin/bootstrap-4.1.3/js/dist/collapse.js’ %}” type=”text/javascript” charset=”utf-8&quot;&gt;&lt;/script&gt;<br>{% endcompress %}</pre><pre>{# END bootstrap js #}</pre><h4>Handling &quot;.scss” Files</h4><p>You may have noticed that we’re using .scss files in HTML directly, and the compress block is not supported by Django out of the box. If you’re using lint checks, your code editor is probably showing warnings by now.</p><p>This tag is provided by <a href="https://github.com/django-compressor/django-compressor">django-compressor</a> to process .scss (and other) files. You may choose to use any other library or none at all. For the sake of this tutorial we’re using django-compressor.</p><p>To install and configure Django Compressor, follow these steps:</p><ol><li>Run pip install django-compressor django-libsass while you’re in Python virtual environment.</li><li>Add compressor to INSTALLED_APPS in settings.py.</li><li>Define <a href="https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_ROOT">COMPRESS_ROOT</a> or <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-STATIC_ROOT">STATIC_ROOT</a> in settings.py.</li><li>Add COMPRESS_PRECOMPILERS = ((‘text/x-scss’, ‘django_libsass.SassCompiler’),) to settings.py.</li><li>Add the following in settings.py:</li></ol><pre>STATICFILES_FINDERS = (<br>    ‘django.contrib.staticfiles.finders.FileSystemFinder’,<br>    ‘django.contrib.staticfiles.finders.AppDirectoriesFinder’,<br>    # other finders..<br>    ‘compressor.finders.CompressorFinder’,<br>)</pre><p>Detailed installation instructions of Django Compressor are available on <a href="https://django-compressor.readthedocs.io/en/latest/quickstart/#installation">readthedocs</a>.</p><h4>Adding Navbar HTML</h4><p>Now, let’s replace the default header with Bootstrap Navbar. Don’t bother with Django code yet, we’ll make the menu dynamic in next section. Delete (or comment out) the existing header code, it looks similar to this:</p><pre>&lt;div id=&quot;header&quot;&gt;<br>    &lt;div id=&quot;branding&quot;&gt;<br>    {% block branding %}{% endblock %}<br>    &lt;/div&gt;<br>    {% block usertools %}<br>    {% if has_permission %}<br>    &lt;div id=&quot;user-tools&quot;&gt;<br>        {% block welcome-msg %}<br>            {% trans &#39;Welcome,&#39; %}<br>            &lt;strong&gt;{% firstof user.get_short_name user.get_username %}&lt;/strong&gt;.<br>        {% endblock %}<br>        {% block userlinks %}<br>            {% if site_url %}<br>                &lt;a href=&quot;{{ site_url }}&quot;&gt;{% trans &#39;View site&#39; %}&lt;/a&gt; /<br>            {% endif %}<br>            {% if user.is_active and user.is_staff %}<br>                {% url &#39;django-admindocs-docroot&#39; as docsroot %}<br>                {% if docsroot %}<br>                    &lt;a href=&quot;{{ docsroot }}&quot;&gt;{% trans &#39;Documentation&#39; %}&lt;/a&gt; /<br>                {% endif %}<br>            {% endif %}<br>            {% if user.has_usable_password %}<br>            &lt;a href=&quot;{% url &#39;admin:password_change&#39; %}&quot;&gt;{% trans &#39;Change password&#39; %}&lt;/a&gt; /<br>            {% endif %}<br>            &lt;a href=&quot;{% url &#39;admin:logout&#39; %}&quot;&gt;{% trans &#39;Log out&#39; %}&lt;/a&gt;<br>        {% endblock %}<br>    &lt;/div&gt;<br>    {% endif %}<br>    {% endblock %}<br>    {% block nav-global %}{% endblock %}<br>&lt;/div&gt;</pre><p>…and replace it with bootstrap Navbar. The following code is taken from Bootstrap documentation, we’ll modify it later.</p><pre>&lt;nav class=”navbar navbar-expand-lg navbar-light bg-light”&gt;</pre><pre>    &lt;a class=”navbar-brand” href=”#”&gt;Navbar&lt;/a&gt;</pre><pre>    &lt;button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarSupportedContent” aria-controls=”navbarSupportedContent” aria-expanded=”false” aria-label=”Toggle navigation”&gt;<br>        &lt;span class=”navbar-toggler-icon”&gt;&lt;/span&gt;<br>    &lt;/button&gt;</pre><pre>    &lt;div class=”collapse navbar-collapse” id=”navbarSupportedContent”&gt;</pre><pre>        &lt;ul class=”navbar-nav mr-auto”&gt;<br>            &lt;li class=”nav-item active”&gt;&lt;a class=”nav-link” href=”#”&gt;Home &lt;span class=”sr-only”&gt;(current)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;<br>            &lt;li class=”nav-item”&gt;&lt;a class=”nav-link” href=”#”&gt;Link&lt;/a&gt;&lt;/li&gt;<br>            &lt;li class=”nav-item dropdown”&gt;<br>                &lt;a class=”nav-link dropdown-toggle” href=”#” id=”navbarDropdown” role=”button” data-toggle=”dropdown” aria-haspopup=”true” aria-expanded=”false”&gt;<br> Dropdown&lt;/a&gt;<br>                &lt;div class=”dropdown-menu” aria-labelledby=”navbarDropdown”&gt;<br>                    &lt;a class=”dropdown-item” href=”#”&gt;Action&lt;/a&gt;<br>                    &lt;a class=”dropdown-item” href=”#”&gt;Another action&lt;/a&gt;<br>                    &lt;div class=”dropdown-divider”&gt;&lt;/div&gt;<br>                    &lt;a class=”dropdown-item” href=”#”&gt;Something else here&lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/li&gt;<br>            &lt;li class=”nav-item”&gt;&lt;a class=”nav-link disabled” href=”#”&gt;Disabled&lt;/a&gt;&lt;/li&gt;<br>        &lt;/ul&gt;</pre><pre>        &lt;form class=”form-inline my-2 my-lg-0&quot;&gt;<br>            &lt;input class=”form-control mr-sm-2&quot; type=”search” placeholder=”Search” aria-label=”Search”&gt;<br>            &lt;button class=”btn btn-outline-success my-2 my-sm-0&quot; type=”submit”&gt;Search&lt;/button&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>Also add the following snippet before closing &lt;/head&gt; tag to avoid django CSS from overriding bootstrap’s CSS.</p><pre>&lt;style type=”text/css”&gt;<br>    .navbar ul li {<br>        list-style-type: none;<br>        padding: 0;<br>    }</pre><pre>    .navbar .dropdown-item {<br>        width: auto;<br>    }<br>&lt;/style&gt;</pre><p>Our template is ready to show bootstrap Navbar.</p><p>Just one thing though. We need to add my_admin to INSTALLED_APPS in settings.py. Let’s do that quickly, and start the development server again.</p><p>Navigate to <a href="http://localhost:8000/admin/">http://localhost:8000/admin/</a>.</p><p>Voila! There’s the Navbar.</p><p>Let’s make it compatible with Django default Admin so that it plays nice with existing template files and makes modification easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIegDu03w_Kq1hAdunYuJw.png" /><figcaption>Django Admin at this stage</figcaption></figure><h4>Making the Code Compatible with Default Django Admin Template</h4><p>First, replace &lt;a class=”navbar-brand” href=”#”&gt;Navbar&lt;/a&gt; with {% block branding %}{% endblock %}. base_site.html specifies this part in Django.</p><p>Let’s quickly switch to base_site.html and replace the following block of code:</p><pre>&lt;h1 id=”site-name”&gt;&lt;a href=”{% url ‘admin:index’ %}”&gt;{{ site_header|default:_(‘Django administration’) }}&lt;/a&gt;&lt;/h1&gt;</pre><p>…with this:</p><pre>&lt;a href=”{% url ‘admin:index’ %}” class=”navbar-brand”&gt;{{ site_header|default:_(‘Django administration’) }}&lt;/a&gt;</pre><p>Back to editing base.html. Replace Navbar menu items with the following code to dynamically populate menu with list of apps.</p><pre>{% if app_list %}<br>    &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;<br>        {% for app in app_list %}<br>            &lt;li class=&quot;nav-item dropdown&quot;&gt;<br>                &lt;a class=&quot;nav-link dropdown-toggle&quot; href=&quot;{{ app.app_url }}&quot; id=&quot;navbarDropdown&quot; role=&quot;button&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;{{ app.name }}&lt;/a&gt;<br>                &lt;div class=&quot;dropdown-menu&quot; aria-labelledby=&quot;navbarDropdown&quot;&gt;<br>                    {% for model in app.models %}<br>                        {% if model.admin_url %}<br>                            &lt;a class=&quot;dropdown-item&quot; href=&quot;{{ model.admin_url }}&quot;&gt;{{ model.name }}&lt;/a&gt;<br>                        {% endif %}<br>                    {% endfor %}<br>                &lt;/div&gt;<br>            &lt;/li&gt;<br>        {% endfor %}<br>    &lt;/ul&gt;<br>{% elif user.is_authenticated %}<br>    &lt;span class=&quot;navbar-text&quot;&gt;You don&#39;t have permission to edit anything.&lt;/span&gt;<br>{% endif %}</pre><p>Replace the bootstrap search form with the following code to display user action links.</p><pre>{% block usertools %}<br>    {% if has_permission %}<br>        &lt;ul class=&quot;navbar-nav my-2 my-lg-0&quot;&gt;<br>            &lt;li class=&quot;nav-item dropdown dropleft text-right&quot;&gt;<br>                &lt;a class=&quot;nav-link dropdown-toggle&quot; href=&quot;#&quot; id=&quot;nav-user-icon&quot; role=&quot;button&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;<br>                    {% block welcome-msg %}&lt;strong&gt;{% firstof user.get_short_name user.get_username %}&lt;/strong&gt;{% endblock %}<br>                &lt;/a&gt;<br>                &lt;div class=&quot;dropdown-menu&quot; aria-labelledby=&quot;nav-user-icon&quot;&gt;<br>                    {% block userlinks %}<br>                        {% if site_url %}&lt;a class=&quot;dropdown-item&quot; href=&quot;{{ site_url }}&quot;&gt;{% trans &#39;View site&#39; %}&lt;/a&gt;{% endif %}<br>                        {% if user.is_active and user.is_staff %}<br>                            {% url &#39;django-admindocs-docroot&#39; as docsroot %}<br>                            {% if docsroot %}&lt;a class=&quot;dropdown-item&quot; href=&quot;{{ docsroot }}&quot;&gt;{% trans &#39;Documentation&#39; %}&lt;/a&gt;{% endif %}<br>                        {% endif %}<br>                        {% if user.has_usable_password %}&lt;a class=&quot;dropdown-item&quot; href=&quot;{% url &#39;admin:password_change&#39; %}&quot;&gt;{% trans &#39;Change password&#39; %}&lt;/a&gt;{% endif %}<br>                        &lt;a class=&quot;dropdown-item&quot; href=&quot;{% url &#39;admin:logout&#39; %}&quot;&gt;{% trans &#39;Log out&#39; %}&lt;/a&gt;<br>                    {% endblock %}<br>                &lt;/div&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br>    {% endif %}<br>{% endblock %}<br>{% block nav-global %}{% endblock %}</pre><p>Run the development server again, then navigate to Django admin. It works, right?</p><p>There’s a tiny issue though. If you navigate to any other page except the homepage, the navigation menu shows different items based on the current page. We did all this effort to show a menu with all items at all pages, didn’t we? Let’s fix that.</p><h4>Showing All Apps In Navigation Menu in Django Admin</h4><p>We’re using app_list tag provided by default in Django, but it does not return all apps’ list at all times. It takes current page as context, and modifies the result accordingly. The solution? We need a custom tag which can return all items at all times.</p><p>Create a python package named templatetags in my_admin app, and create a file utils.py in it. Paste the following code in this file.</p><pre>from django import template<br>from django.contrib import admin</pre><pre><br>register = template.Library()</pre><pre><br>class CustomRequest:<br>    def __init__(self, user):<br>    self.user = user</pre><pre><a href="http://twitter.com/register"><br>@register</a>.simple_tag(takes_context=True)<br>def get_app_list(context, **kwargs):<br>    custom_request = CustomRequest(context[&#39;request&#39;].user)<br>    app_list = admin.site.get_app_list(custom_request)<br>    return app_list</pre><p>Next, in settings.py add the following to OPTIONS in TEMPLATES variable:</p><pre>&#39;libraries&#39;: {<br>    &#39;common_utils&#39;: &#39;my_admin.templatetags.common_utils&#39;,<br>},</pre><p>TEMPLATES might look something like this after adding it:</p><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [],<br>        &#39;APP_DIRS&#39;: True,<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>            &#39;django.template.context_processors.debug&#39;,<br>            &#39;django.template.context_processors.request&#39;,<br>            &#39;django.contrib.auth.context_processors.auth&#39;,<br>            &#39;django.contrib.messages.context_processors.messages&#39;,<br>            ],<br>            &#39;libraries&#39;: {<br>                &#39;common_utils&#39;: &#39;my_admin.templatetags.common_utils&#39;,<br>            },<br>        },<br>    },<br>]</pre><p>Next, go back to base.html and make the following changes:</p><ol><li>Put {% load common_utils %} somewhere at the top of file to load our custom template tags.</li><li>Put {% get_app_list as all_app_list %} above {% if app_list %}.</li><li>Change app_list variable to all_app_list.</li><li>Reload Django Admin in browser.</li></ol><p>Your header in base.html might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5247bad635019db61ebb02d1cef431da/href">https://medium.com/media/5247bad635019db61ebb02d1cef431da/href</a></iframe><p>We’re done! Everything should work as expected.</p><h4>Some Tips and Complete Code</h4><p>You might be tempted to edit the core files directly or not using existing Django template blocks, but the advantage of the above approach is that we get a modular standalone app. You can literally use this app with any standard Django Admin project and you’ll get a working navigation menu bar with no extra efforts.</p><p>We’ve used bootstrap in this tutorial to avoid spending time in creating UI. In your project you may use any other navigation menu component or create your own component from scratch.</p><p>What we are essentially doing is getting list of apps from our custom template tag and showing them in the menu as links. You can use the same approach and create material design drawer menu instead of Navbar! The best part is that you can override any part of Navbar as you would have done with default Django Admin template.</p><p>The project I created for this tutorial is available on github for reference: <a href="https://github.com/TheKalpit/Bootstrap-Navbar-in-Django-Admin">https://github.com/TheKalpit/Bootstrap-Navbar-in-Django-Admin</a></p><p>Thanks for reading!</p><p><strong>Were you able to create Navbar easily using this tutorial? Do you have any other tips to improve this tutorial? Let me know your experience in comments below.</strong></p><p>If you like this post, you might also like, <a href="https://blog.crowdbotics.com/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework/"><strong>How to write an API in 3 lines of code with Django REST framework</strong></a></p><p>Thanks to <a href="https://medium.com/u/c96e7232f511">William Wickey</a> for help editing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7kqyahThCaSx77QSjO_8A.png" /></figure><h4>Building A Web Or Mobile App?</h4><p><em>Crowdbotics is the fastest way to build, launch and scale an application.</em></p><p><em>Developer? Try out the </em><a href="https://www.crowdbotics.com/app-builder/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Crowdbotics App Builder</em></strong></a><em> to quickly scaffold and deploy apps with a variety of popular frameworks.</em></p><p><em>Busy or non-technical? Join hundreds of happy teams building software with Crowdbotics PMs and expert developers. Scope timeline and cost with Crowdbotics</em><strong><em> </em></strong><a href="https://www.crowdbotics.com/managed-app-development/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Managed App Development</em></strong></a><em> for free.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=770b872a9531" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crowdbotics/how-to-add-a-navigation-menu-in-django-admin-770b872a9531">How to Add A Navigation Menu In Django Admin</a> was originally published in <a href="https://medium.com/crowdbotics">Crowdbotics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When To Use Django (And When Not To)]]></title>
            <link>https://medium.com/crowdbotics/when-to-use-django-and-when-not-to-9f62f55f693b?source=rss-dc046f2bf80b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f62f55f693b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kalpit Jain]]></dc:creator>
            <pubDate>Tue, 28 Aug 2018 18:06:31 GMT</pubDate>
            <atom:updated>2019-06-12T10:38:22.528Z</atom:updated>
            <content:encoded><![CDATA[<h4>Helping developers evaluate whether Django is the right framework for their next project. Chances are, it is.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25Le7KoMK_z6BIaM8x74RA.png" /></figure><p>Choosing a language and framework because you used it on your last project — or because you are more familiar with it — is not the way to go.</p><p>Before starting a new software project, you want to evaluate which language and framework is the best fit for your desired outcomes. What matters most to you? Security, rapid development, scalability, versatility, support?</p><p>It’s better to make an informed choice before you begin your build rather than regretting it later (or worse “hacking” stuff into the project down the road because the stack you used doesn’t support it properly).</p><p>After years of experience with different technologies (including both mobile &amp; web development), I believe <a href="https://docs.djangoproject.com/en/2.1/">Django</a> offers a complete suite of features which no other web framework offer.</p><p>I know that’s a big claim. Let me back this up.</p><blockquote>“Django powers many of the Web’s most-used sites, like Instagram and Pinterest, even Facebook uses Django for its many behind-the-scenes utilities. Django came from publishing, so it’s no surprise that sites like The Washington Post and Smithsonian Magazine use Django.” — <a href="https://medium.com/swlh/what-is-django-and-why-is-it-so-popular-2b225620cca0">Amit Ashwini,</a> VP of Marketing @ <a href="https://medium.com/u/80c8a8c2716e">Zibtek</a></blockquote><h4><strong>High-level: When to use Django</strong></h4><p>If you can check even a few of the statements below (without strongly disagreeing with any), chances are that Django is good for your project.</p><ul><li>You need to develop a web app or <a href="https://medium.com/crowdbotics/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework-59b0971edfa4">API backend</a>.</li><li>You need to move fast, deploy fast, and also make changes as you move ahead.</li><li>The app must be secure from most common vulnerabilities and attacks by default. For example CSRF, SQL Injection, XSS, Clickjacking, etc.</li><li>Your app might scale up/down at any point of time.</li><li>You might integrate cutting edge tech in future, eg. Machine Learning.</li><li>You need to use a reliable framework which is actively developed, and used by many top websites and companies on the planet.</li><li>You need both web app and API backend in same codebase to comply with “Single source of truth” (aka DRY)</li><li>You don’t want to work with database queries directly, and need ORM support.</li><li>You want to use open source software.</li><li>You’re concerned about finding solutions if you get stuck, so a good documentation and supportive community should be present.</li></ul><p>In addition to the above points, your own (or your team’s) skill-set should be considered as well.</p><p>If you’re already a web developer with knowledge of “how the web works”, then working with Django will be comparatively seamless. You only need to understand how Django is structured (and some other things, of course) and you’re good to go.</p><h4>Websites that Rely on Django Framework</h4><p>Django has been around for over a decade now. During this period lot of top websites have used it in production, some notable examples are:</p><ul><li><a href="https://medium.com/u/ef81ef829bcb">Pinterest Engineering</a></li><li><a href="https://medium.com/u/95f4ec6ae6f6">Mozilla</a></li><li><a href="https://reinout.vanrees.org/weblog/2011/06/07/bitbucket.html">Bitbucket</a></li><li><a href="https://medium.com/u/b32aa0132f1b">Udemy</a></li><li><a href="https://www.reddit.com/r/django/comments/bhvhz/the_onion_uses_django_and_why_it_matters_to_us/">The Onion</a></li><li><a href="https://medium.com/u/6e0d0a4b41f">Disqus</a></li><li><a href="https://medium.com/u/f0c3167dc11d">Washington Post</a></li><li><a href="https://www.quora.com/What-is-NASAs-technology-stack/answer/Yuvraj-Gurung">NASA</a></li><li><a href="https://medium.com/u/60a317bb70e4">Spotify</a></li><li><a href="https://medium.com/u/a4c6efa67fe0">Instagram Engineering</a></li><li><a href="https://www.djangosites.org/s/www-nationalgeographic-com/">National Geographic</a></li><li><a href="https://medium.com/u/622ebb3ad4d4">The Guardian</a></li><li><a href="https://medium.com/u/5f9f1633498c">JSFiddle</a></li></ul><p>Are you still wondering if it’ll be worth to invest your precious hours to get up to speed with Django? First, consider reasons why Django may NOT be a fit for your project:</p><h4>When not to use Django</h4><ul><li>Your app is extremely huge, and you cannot keep everything in a single codebase.<br><em>You might want to break your app into microservices. Each layer might be better handled by a dedicated team and process. It’d be better to use different technologies for each use-case. Django might help in some specific use-cases, but it might not be wise to develop everything with Django (or any other framework alone).</em></li><li>You need to build a very basic app, which does not require database, file operations, or anything even remotely complex.<br><em> Micro frameworks are better suited for these use-cases. Flask is one of the most popular micro framework written in Python. Similar micro frameworks are available in other technologies, eg. Slim in PHP, Apache Spark in Java, Express.js in Node.js, etc.</em></li><li>You want to build everything from scratch, and you know what you’re doing.</li><li>You or your team members are not familiar with Django/Python at all, and you can’t afford to invest time and resources to gather the required skills.<br><em> The best solution in this scenario is to go with what you know best. If you take up a new technology or framework, the chances of messing things up increase manyfold.</em></li></ul><p>If the above does not apply to your project, chances are Django might be a fit.</p><h3>Reasons To Use Django</h3><h4><strong>Django Framework is built with Python:</strong></h4><p>I know you’re familiar with this fact.</p><p>I’m just taking this opportunity to highlight some of the key benefits of Django which it inherited from Python. I’ll keep it short.</p><ul><li>Python is one of the most popular and growing languages in the world.<br>Sources:<br><a href="https://www.tiobe.com/tiobe-index/">TIOBE index<br></a><a href="https://www.codingdojo.com/blog/7-most-in-demand-programming-languages-of-2018/">Indeed.com Jobs’ data analysis by Coding Dojo<br></a><a href="https://octoverse.github.com/">GitHub Octoverse<br></a><a href="https://insights.stackoverflow.com/survey/2018/#technology">Stack Overflow Developer Survey 2018</a></li><li>Python is really easy to learn. It is usually first language of choice for developers.</li><li>Don’t let the previous statement misguide you in believing that it’s only for beginners. Python is used in cutting edge tech as well. Many giants including Google use Python in their tech stack extensively.</li><li>Python is a highly recommended language for developing web scrapers.</li><li>It plays nice with other languages.<br><em> Developing with Python does not mean that you have to stick with everything that’s built with Python only. You may use libraries built with many other languages, including C/C++/Java</em></li><li>Python is portable, and easy to read</li><li>Python can even run on JVM. Check out <a href="https://wiki.python.org/jython/">Jython</a>.</li><li>Python is extensively used and supported in cutting-edge tech like Big Data, Machine Learning, etc.</li><li>Access to huge PyPI library.</li></ul><blockquote>“Program development using Python is 5–10 times faster than using C/C++, and 3–5 times faster than using Java.”. — <a href="https://www.python.org/doc/essays/omg-darpa-mcc-position/">source</a></blockquote><h4><strong>Django has “Batteries Included”:</strong></h4><p>“Batteries included” means that Django comes with most of the libraries and tools required for common use cases, out of the box. Django ORM, Middlewares, Authentication, HTTP libraries, Multi-site support, i18n, Django Admin, template engine etc. are some of the “batteries”. No other framework that I know of offers this much support out of the box.</p><p>Some people prefer to put this under “Cons”, while others put it under “Pro”. Each side has its reasons, and I agree with both sides to a deg</p><p>It is a <em>con</em> because it makes the framework a monolith.</p><p>My argument is that if you require those features which make it a monolith, you’re going to use some other library (or write your own) anyway.</p><p>Why not use something which is baked right in, battle tested, powers some of the largest websites on the planet, actively developed, and supported by the community?</p><p>If you don’t require most of the features offered by Django, you should consider using a micro framework instead.</p><p>Don’t reinvent the wheel, remember? Spend your time on the stuff that matters, let Django handle the rest.</p><h4><strong>Django Admin</strong></h4><p>Though I mentioned it in previous section, it needs more attention. Many frameworks, like Laravel, Yii, etc. have attempted to make working with admin panel easier. I’ve developed many projects in various frameworks, but none of them are even remotely closer to Django framework in terms of working with Admin panel.</p><p>Some people argue that Django Admin isn’t flexible enough, and customizing any part of it requires a lot of effort. I used to agree with this statement during my early days with Django, but eventually, as I got familiar with the framework, I found out that this is incorrect. Yes, there’s a learning curve — but it’s worth every second.</p><p>Django Admin is actually very well structured. In some of my projects I’ve used Django admin as-is, and in others I’ve completely replaced it with custom templates developed from scratch. In any case, it did not take longer than it would have if I had developed it with any other framework I knew.</p><p>The best part? You get permissions and authentication module out of the box. If built from scratch, this could take weeks (or days) at least.</p><h4><strong>DRY Principle (Don’t Repeat Yourself)</strong></h4><p>I’ve seen many frameworks boast about being “DRY” compliant. I’ve worked with many of them, but none get it right.</p><p>Most frameworks, unfortunately, don’t care enough to really follow the “DRY” principle. In my opinion, if you’re building an app which you’ll be updating regularly (most apps today), you must follow DRY to avoid issues.</p><p>In Laravel, for instance, you’re required to write validations for each route separately. This is the case with most other frameworks. To make your code DRY compliant, you need to make efforts. It’s hard to keep check especially when you’re working in a team.</p><p>Django framework, on the other hand, is designed in such a way that you have to go out of your way to violate DRY principle.</p><p>That’s the way it should be, right? Need an example?</p><p><strong>Here’s how validations &amp; database migrations work in Django:</strong></p><ol><li>Create a Model class with required fields. Specify any extra validations and constraints as needed.</li><li>Migrations are generated with just one CLI command: `python manage.py makemigrations`.</li><li>Database is updated with the changes with just one CLI command: `python manage.py migrate`.</li><li>The validations and constraints are automatically checked on each CRUD operation — be it in Django Admin or Django REST Framework. You don’t need to write validations ever again.</li><li>The same model class is used to generate Django Admin CRUD views. No custom HTML/CSS required.</li></ol><p>If you compare this with any other framework, I don’t think it’ll be able do all this with just the following lines of code.</p><pre>class Employee(models.Model):<br>    name = models.CharField(max_length=127)<br>    email = models.EmailField(null=True, blank=True)<br>    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)<br>    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)</pre><p>It’s not just about “not repeating yourself”. It helps you avoid bugs in the future. We all have been in situations when you changed something at some place, but forgot to do that at other place and found it out only after many customers ran into the issue.</p><p>In Django, referring to the above code, if you ever need to change a field’s `max_length` to something else — just do it here. It’ll automatically be applied to all routes’ validation &amp; database.</p><h4><strong>Django Framework ORM</strong></h4><p>Django provides a fully functional ORM right out of the box.</p><p>I’ve worked with many ORMs in different technologies, including Eloquent, greenDAO, Yii AR, etc. All of them handle basic queries pretty well, but at some point I always find myself writing raw queries because the ORM fails to address the use-case.</p><p>I’ve not run into such a case yet with Django ORM. It’s so well built that it makes you forget that you’re actually working with database queries. That’s how an ORM should be. Below are some examples of Django ORM:</p><pre># gets top 5 results where rank = 10 and age &lt;= 30<br>top_young_employees = Employee.objects.filter(rank=10, age__lte=30)[:5]</pre><pre># inserts a record with specified values<br>employee = Employee.objects.create(name=’John Doe’, age=35, country=’IN’)</pre><pre># prints field value<br>print(employee.name)</pre><h4>Rapid Development</h4><p>This is something almost all web frameworks shout out loud, and they’re probably right with their own definition of “rapid”.</p><p>With Django though, you can get stuff done ridiculously fast. You just saw how rapidly we were able to define admin UI, database table, and validations above.</p><p>That was just the tip of the iceberg.</p><p>Although it’s not particularly a feature by itself, it’s actually a by-product of following DRY, ORM, template engine, and “batteries included” philosophy.</p><h4><strong>Django Framework Security</strong></h4><p>Let’s face it, developers are sometimes lazy. At least I am. More often than not, I procrastinate doing some tasks which aren’t crucial for development. These tasks usually open doors for security vulnerabilities.</p><p>The part I like most about Django is that it doesn’t compromise on security to offer rapid development. Security features are enabled by default so it doesn’t matter if you’re lazy.</p><h4><strong>Open Source, Well Documented, Huge Community, and More</strong></h4><p>Being open source and insanely popular, Django has created a helpful community. I’m assuming you’re aware of the advantages of open source software. Django has the same advantages.</p><p>Django’s official documentation is more than enough for developers. You can easily find solutions if you get stuck. On top of that, Stack Overflow is flooded with questions &amp; answers related to Django.</p><p>So far we’ve seen that Django created a lot of libraries of its own, so it might surprise you that it didn’t create any library for testing. It doesn’t mean that Django framework doesn’t support testing — it does. They have a complete section dedicated to testing in docs. Following the principle “Don’t reinvent the wheel”, it’d be pointless to develop a testing library when Python itself provides a great one itself. Django just plays nice with it. It also works well with other popular third-party libraries like pytest.</p><h3><strong>State of Django Today and Other Popular Frameworks</strong></h3><p>I’ve tried my best to address the issues I faced while working with other frameworks in contrast with Django. After working with Yii, CodeIgniter, WordPress, CS-Cart, Laravel, etc. I’ve found Django to be a lot better than any of them.</p><p>It’s just my opinion though.</p><p>If you’re into statistics, here’s Stack Overflow’s yearly survey showing Django amongst the top used &amp; loved frameworks:</p><ul><li><a href="https://insights.stackoverflow.com/survey/2018/#technology-frameworks-libraries-and-tools"><em>Frameworks, Libraries, and Tools</em></a></li><li><a href="https://insights.stackoverflow.com/survey/2018/#technology-most-loved-dreaded-and-wanted-frameworks-libraries-and-tools"><em>Most Loved, Dreaded, and Wanted Frameworks, Libraries, and Tools</em></a></li></ul><p>If you’re as paranoid as I am, you probably spend more than enough time on application architecture and code structure.</p><p>Apart from my experience with PHP framework mentioned above, I’ve also developed Android apps in Java, and front-end apps with React.js. In all of them, I’ve spent more than required time refactoring codebase, finding the best architecture, running into scalability issues after a few months, then refactoring again.</p><p>I recently moved a production app running for over a year from Laravel to Django. I was able to deploy the new codebase within 10 days and very few lines of code (re: reduced complexity)! Had it been the other way around, it would have taken more than a month for sure.</p><p>If you try to directly compare other frameworks with Django, you won’t get anywhere.</p><p>Performance benchmarks may show a Java framework faster than Django. You might be familiar with PHP so it might take you longer to develop in Django app as compared to a PHP framework you’re familiar with. For a really simple app, you might find setting up Django a bit tedious as compared to a single script file. Different polls might show different results based on the audience they reached.</p><p>It’s not just about frameworks of other technologies though. Even if you’re familiar with Python, you might find Flask micro-framework more popular or suggested more than Django. It’ll make you wonder which one should you go for.</p><p>My advice? Don’t compare these two.</p><p>Django is a full-fledged framework with “batteries included”, Flask on the other hand is a micro-framework . Define your use-case. Identify your skill-set. Then, choose one.</p><h4><strong>Conclusion</strong></h4><p>In my opinion, Django is the perfect balance between performance, architecture, development effort, security and scalability.</p><p>If you’re starting a software project from scratch, I’d personally recommend Django.</p><p>I’ve tried my best to pen down my experience with Django in contrast with other web frameworks I’ve worked with.</p><p><em>If you find any errors, or feel any need for improvement, let me know in your comments below.</em></p><p><em>Have you worked with Django? Let me know your experience in comments.</em></p><p>If you like this post, you might also like, <a href="https://blog.crowdbotics.com/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework/"><strong>How to write an API in 3 lines of code with Django REST framework</strong></a></p><p><em>Thanks to </em><a href="https://medium.com/u/c96e7232f511"><em>William Wickey</em></a><em> for editing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7kqyahThCaSx77QSjO_8A.png" /></figure><h4>Building A Web Or Mobile App?</h4><p><em>Crowdbotics is the fastest way to build, launch and scale an application.</em></p><p><em>Developer? Try out the </em><a href="https://www.crowdbotics.com/app-builder/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Crowdbotics App Builder</em></strong></a><em> to quickly scaffold and deploy apps with a variety of popular frameworks.</em></p><p><em>Busy or non-technical? Join hundreds of happy teams building software with Crowdbotics PMs and expert developers. Scope timeline and cost with Crowdbotics</em><strong><em> </em></strong><a href="https://www.crowdbotics.com/managed-app-development/?utm_source=medium?utm_campaign=cb-medium?utm_content=footer"><strong><em>Managed App Development</em></strong></a><em> for free.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f62f55f693b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crowdbotics/when-to-use-django-and-when-not-to-9f62f55f693b">When To Use Django (And When Not To)</a> was originally published in <a href="https://medium.com/crowdbotics">Crowdbotics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>