<?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 Farhan Khan on Medium]]></title>
        <description><![CDATA[Stories by Farhan Khan on Medium]]></description>
        <link>https://medium.com/@farhan0581?source=rss-32aa306bb0c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*of8gvNWU2Uvq5gWw.</url>
            <title>Stories by Farhan Khan on Medium</title>
            <link>https://medium.com/@farhan0581?source=rss-32aa306bb0c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:10:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farhan0581/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[Autocomplete List Filter in Django Admin]]></title>
            <link>https://medium.com/cashify-engineering/autocomplete-list-filter-in-django-admin-2a88ead52246?source=rss-32aa306bb0c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a88ead52246</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[panel]]></category>
            <dc:creator><![CDATA[Farhan Khan]]></dc:creator>
            <pubDate>Fri, 23 Nov 2018 08:59:22 GMT</pubDate>
            <atom:updated>2018-11-23T08:59:22.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6eUvRpDCHO1kDKfZN8m9WQ.png" /></figure><p>With the coming of Django version 2.0, we have now got an <a href="https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields">autocomplete</a> functionality in the admin panel. As stated in the docs:</p><blockquote><strong>autocomplete_fields</strong> is a list of <strong>ForeignKey</strong> and/or <strong>ManyToManyField</strong> fields you would like to change to <a href="https://select2.org/">Select2</a> autocomplete inputs.</blockquote><blockquote>By default, the admin uses a select-box interface (<strong>&lt;select&gt;</strong>) for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the drop-down.</blockquote><blockquote>The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously. This is faster and more user-friendly if the related model has many instances.</blockquote><p>Now we can use the autocomplete functionality in the Django admin’s ‘Change’ or ‘Add Page’. However, for the list filters, we still have the old way of displaying the items, as listed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*g0RHI8F7YFgF_9mcrhhgQw.png" /><figcaption>Default Admin List Filter</figcaption></figure><p>Now consider the scenario when you have a large number of records. The list grows to such an extent that it becomes cumbersome and difficult to use.</p><p>So to solve this, there is a <a href="https://github.com/farhan0581/django-admin-autocomplete-filter">simple app</a> which uses Django’s autocomplete widget to render the list filter.</p><p>Install it via pip as: pip install django-admin-autocomplete-filter</p><p>Then add admin_auto_filters to your INSTALLED_APPS inside settings.py of your project.</p><h3>Usage:</h3><p>Let’s say we have the following models:</p><pre>class Artist(models.Model):<br>    name = models.CharField(max_length=128)</pre><pre>class Album(models.Model):<br>    name = models.CharField(max_length=64)<br>    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)<br>    cover = models.CharField(max_length=256, null=True, default=None)</pre><p>Moreover, you would like to filter results in Album Admin by the ‘artist’; then you can define search fields in Artist and define filter as:</p><pre>from admin_auto_filters.filters import AutocompleteFilter</pre><pre>class ArtistFilter(AutocompleteFilter):<br>    title = &#39;Artist&#39; # display title<br>    field_name = &#39;artist&#39; # name of the foreign key field</pre><pre>class ArtistAdmin(admin.ModelAdmin):<br>    search_fields = [&#39;name&#39;] # this is required for django&#39;s autocomplete functionality<br>	...</pre><pre>class AlbumAdmin(admin.ModelAdmin):<br>    list_filter = [ArtistFilter]<br>	...</pre><p>After following these steps, you may see the filter in Album Admin page as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*_Zu4k6qXWtnTT_VDgHZnvg.png" /><figcaption>Using Autocomplete Widget</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*OVuN7J76PaSdaAMQ7rEW6g.png" /><figcaption>Search As You Type</figcaption></figure><p>The autocomplete functionality uses the <a href="https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_search_results">get_search_results</a> method to get the results. So to modify the search results you may consider overriding this method in the concerned admin class.</p><p>Similarly, the pagination is controlled by model admin’s <strong>get_paginator</strong> method. You may override these and provide your custom view using the <strong>autocomplete_view</strong> method in your admin class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a88ead52246" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cashify-engineering/autocomplete-list-filter-in-django-admin-2a88ead52246">Autocomplete List Filter in Django Admin</a> was originally published in <a href="https://medium.com/cashify-engineering">Cashify Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips Before Starting a Django Project]]></title>
            <link>https://medium.com/cashify-engineering/tips-before-starting-a-django-project-a95b44811c47?source=rss-32aa306bb0c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a95b44811c47</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-admin]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Farhan Khan]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 09:59:35 GMT</pubDate>
            <atom:updated>2018-10-04T06:18:49.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Q6zZPG6uZiBDqTxSl8oELQ.png" /></figure><p>Often in the middle of a large project, we come across things that should have been taken care of at the very beginning. Here at Cashify, we came across many such things that should have been done before starting a project. Hence, we would like to share our experience so that others do not face the same frustration we did.</p><p>The picture below pretty much depicts our condition during many situations.. ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*FDouaKwYtyprvvbzlbeHvQ.jpeg" /></figure><p>So, here are some tips that I have summoned that you might find useful before you start your project in Django:</p><h3>1. Project Layout</h3><p>In the default Django project setup — views, models and forms are placed in views.py, models.py and forms.py respectively in an app directory. However, as your project grows larger, managing hundreds of models, views etc. in a single file becomes cumbersome. So it is better to place your models, views, forms and admin files in separate directories named models, views, forms and admin.</p><p>Inside these directories, place __init__.py that tells Django which files to pick. A typical structure looks like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*Uk2yCHNaxLFnvOSdLfoTWA.png" /><figcaption>django project layout.</figcaption></figure><p>If you are starting fresh and have an existing database, then <a href="https://medium.com/cashify-engineering/generating-django-models-from-a-database-f4d03883cc5b">this</a> simple management command built on top of <strong>inspectdb</strong> will help you a lot. It will automatically create the required directory structure, and the model’s files will be pre-populated. You can thank me afterwards…. ;)</p><h3>2. Custom User Model</h3><p>Many times you will need to override the auth user model that comes with the Django authentication backend. For example, you would like to add some fields to the auth user table or change the existing ones. Changing the user model mid-project becomes a tedious task as it may lead to migration errors.</p><p>Django’s <a href="https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project">documentation</a> on this suggests the same. It is always better to start with a custom user model, so that we can change it as the need arises in the future. To substitute your user model:</p><pre><strong>from</strong> <strong>django.contrib.auth.models</strong> <strong>import</strong> AbstractUser<br><br><strong>class</strong> <strong>CustomUser</strong>(AbstractUser):<br>    <strong>pass</strong></pre><p>Then point to the user model in settings.py. Do this before creating any migrations or running <strong>manage.py migrate</strong> for the first time. Also, register your user model in your admin.</p><pre>AUTH_USER_MODEL = &#39;your_app.CustomUser&#39;</pre><p>So whenever the need arises you can modify the user model and run migrations to update the table.</p><h3>3. Managing your settings.py</h3><p>It is equally important to manage your settings.py. You might have different features for your project depending on the environment. You might be testing some features on the testing server which will go to staging and finally on production. As a result, there could be differences in the dependencies. So, it is better to break your settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*Lhik5vYDiw5x3uAN9r2LUA.png" /><figcaption>breaking your settings.py</figcaption></figure><p>In your main settings.py you can import from other settings_env_name.py as:</p><pre>try:</pre><pre>    import importlib<br>    env_mode = env(&#39;MODE&#39;, <em>default</em>=&#39;local&#39;)<br>    filename = &quot;your_project.settings.settings_%s&quot; % (env_mode)<br>    module = importlib.import_module(filename)<br>    names = [name for name in dir(module) if not   name.startswith(&#39;_&#39;)]</pre><pre>    globals().update({name: getattr(module, name) for name in names})<br>except:</pre><pre>    pass</pre><p>Here MODE is the name of the environment variable which has a value such as beta, local, test, prod etc. Since your settings.py is inside a directory now, make sure you change the <strong>BASE_DIR</strong> to:</p><pre>BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))</pre><h3><strong>4. Using Virtual Environment</strong></h3><p>When we start any project, we install other dependencies based on our requirements. Now the problem arises when we try to deploy the project on the server. So it is always better to have a list of all the dependencies that are to be installed.</p><p>Moreover, if we have many projects in our system, it is better to keep their dependencies separate, so that they do not affect each other in the future in case of an upgrade or version change. For example, some old projects may be using Django 1.11. In such a scenario, you may want to try out Django 2.0 without affecting these projects.</p><p>So if you are using python3 and Ubuntu, then follow these steps:</p><pre>sudo pip3 install virtualenv # to install virtualenv</pre><p>Now create a virtual environment using the following command:</p><pre>virtualenv -p python3 your_env_name</pre><p>This will create a virtual environment with the name provided. To activate it:</p><pre>source your_env_name/bin/activate</pre><p>Now start installing your dependencies, and whenever you want to deploy it, you can list all the dependencies using pip freeze.</p><pre>pip freeze &gt; requirements.txt</pre><p>It will save the output of pip freeze in a file named — requirements.txt. Now pip can also install the packages in the file using -r flag:</p><pre>pip install -r requirements.txt</pre><p>This will then install all the dependencies listed in the file.</p><p>You may even have a different requirements.txt based on the environment just like settings.py:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*kARvAGST62HUCxkQulY63w.png" /><figcaption>different dependency files.</figcaption></figure><h3>5. Using Django Debug Toolbar</h3><p><a href="https://github.com/jazzband/django-debug-toolbar">This</a> is an excellent and useful utility which helps to keep track of the queries which are going to the database. It helps us to know the SQL query made by the django ORM behind the scenes. This is useful to identify slower SQL queries which need optimization.</p><p>It is particularly helpful when you are using the Django admin panel because in the admin panel, you are unaware of the queries being made by django. It’s all magic going on behind the scenes. But as you grow and the data grows exponentially, the panel might become slow. So better take care of it now, rather than facing problems afterward.</p><h3>Conclusion:</h3><p>So in this article, we saw some things which we should do before starting any django project. These were based on my experience working at Cashify. I will try adding more points to this article in future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a95b44811c47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cashify-engineering/tips-before-starting-a-django-project-a95b44811c47">Tips Before Starting a Django Project</a> was originally published in <a href="https://medium.com/cashify-engineering">Cashify Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Django Models from a Database]]></title>
            <link>https://medium.com/cashify-engineering/generating-django-models-from-a-database-f4d03883cc5b?source=rss-32aa306bb0c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d03883cc5b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Farhan Khan]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 03:49:18 GMT</pubDate>
            <atom:updated>2018-08-30T03:49:18.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ISAOVzdrdL86U1oUpg4M9A.png" /></figure><p>It is quite possible that you have an existing database and want to generate models based on that. Well it is possible to integrate Django into legacy databases. Django includes a couple of utilities to automate as much of this process as possible.</p><p>It comes with a management command utility called <a href="https://docs.djangoproject.com/en/2.1/howto/legacy-databases/#auto-generate-the-models"><strong><em>inspectdb</em></strong></a>, which auto generates the models as well as outputs that are generated at the console to be redirected to a file.</p><p>Now, this was the usual stuff you might have came across numerous threads on Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wPdhOaTb_GNf_2KMZsXTFg.jpeg" /></figure><p>But let’s say you have a very large database with many tables, managing models through a single models.py becomes a cumbersome task.</p><p>Tada! Here comes the different part...</p><h3>Generating models efficiently</h3><p>Now let us consider breaking our models.py into different files based on model and doing the same with admin, forms and views. This way of managing our large project becomes easy.</p><p>For this, there is a simple utility called <a href="https://github.com/farhan0581/django-inspectdb-refactor">django inspectdb refactor</a> built on top of inspectdb which automatically creates models separately into the specified app.</p><p>To get started, install the package using pip install django-inspectdb-refactor.</p><p>Then register inspectdb_refactor to your INSTALLED_APPS inside settings.py of your project.</p><p>The command accepts two command line arguments:</p><ul><li>app : This is a required argument. You need to provide app_label in order to make models in that particular app.</li><li>database: To specify a particular database. Otherwise it picks default from settings.</li></ul><p>For example, if you have an app called products and database product_db then run:</p><p>python manage.py inspectdb_refactor --database=products --app=product_db</p><p>This will then create all the files based on your model name inside the specified app directory. You may make the required changes in the models based on your requirements.</p><p>Depending on your models, you may get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*wrMJqNIpVoy81UU0bzdWfg.png" /><figcaption>example app structure having three models.</figcaption></figure><p>All your boring work of copy and paste has been done and you can straightaway dive to code the logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d03883cc5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cashify-engineering/generating-django-models-from-a-database-f4d03883cc5b">Generating Django Models from a Database</a> was originally published in <a href="https://medium.com/cashify-engineering">Cashify Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>