<?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 Alfarhan Zahedi on Medium]]></title>
        <description><![CDATA[Stories by Alfarhan Zahedi on Medium]]></description>
        <link>https://medium.com/@alfarhanzahedi?source=rss-9a7400cae3cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zPAzn5mtmKJyQRI-075OzA.jpeg</url>
            <title>Stories by Alfarhan Zahedi on Medium</title>
            <link>https://medium.com/@alfarhanzahedi?source=rss-9a7400cae3cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:10:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alfarhanzahedi/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[Yet Another Django Project Template]]></title>
            <link>https://medium.com/@alfarhanzahedi/yet-another-django-project-template-4dfcf505cb2e?source=rss-9a7400cae3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dfcf505cb2e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Alfarhan Zahedi]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 17:10:28 GMT</pubDate>
            <atom:updated>2020-02-02T17:10:28.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E03TCY2FUB0jHyg8.png" /><figcaption><a href="https://www.djangoproject.com/s/img/logos/django-logo-negative.png">https://www.djangoproject.com/s/img/logos/django-logo-negative.png</a></figcaption></figure><p>I have been learning to develop web applications and APIs in Django for the last two years. And this article is going to be all about the project template and the initial boilerplate that I have come to use after two years of toiling with Django.</p><p>Needless to say, I will also be including the external packages and tools that I use, by default, in each of my projects.</p><p>Also, I will not be explaining the usage of the aforementioned packages and tools. Rather, I will be providing the links to blog posts and documentations from where I got to know about them.</p><p>So, to make more sense of this article, you should go through each of the link’s content as you proceed.</p><p>Also, please note that I am just a beginner, and hence prone to mistakes. So, bear with me, and comment if you come across any mistakes or have any questions, feedback or suggestions.</p><p>Let’s begin.</p><p>$django-admin startproject <strong>notes</strong></p><p>This will generate the following project structure —</p><pre><strong>notes/<br>├── notes/<br>│   ├── settings.py<br>│   ├── urls.py<br>│   ├── wsgi.py<br>│   └── __init__.py<br>└── manage.py</strong></pre><p>I would make do with this structure and the corresponding boilerplate during my initial days with Django.</p><p>Do not laugh at me when I say that I used to hard-code the various project parameters under settings.py. I used to update these hard-coded values (as a separate commit), like changing DEBUG = False from DEBUG = True, whenever I had to deploy the app to production 😛.</p><p>I would then update them again (as a separate commit) whenever I needed to add a new feature or fix a bug in the application.</p><p>Yeah, I know that it is cumbersome and stupid 😒.</p><p>It was on my way to break this vicious cycle of updates that I stumbled upon the python package — python-decouple and life has been so much easier since then!</p><p>python-decouple allows us to organize our settings so that we can change parameters without having to redeploy our app. Cool, right?</p><p><a href="https://simpleisbetterthancomplex.com/2015/11/26/package-of-the-week-python-decouple.html">This</a> article on <a href="https://simpleisbetterthancomplex.com/"><strong>Simple is Better Than Complex</strong></a> introduced me to this awesome package. Have a read!</p><p>So, now, the initial project structure became —</p><pre>notes/<br>├── notes/<br>│   ├── settings.py<br>│   ├── urls.py<br>│   ├── wsgi.py<br>│   └── __init__.py<br><strong>├── .env<br>├── .env.example<br>├── .gitignore</strong><br>└── manage.py</pre><p>Three files — .env, .env.example and .gitignore were added as a result of the usage of the package — python-decouple.</p><p>You know the .pyc files that Python generates? They can be found in __pycache__ directory inside each of the packages in a Django project.</p><p><strong>What are </strong><strong>.pyc files?<br></strong>Python source files are compiled into byte-code and saved on disk in<br>form of .pyc files which are then used by the Python virtual<br>machine. These files are generated automatically on the fly on<br>every machine where the code runs.</p><p>Being a newbie that I was, I used to commit .pyc files to git! <br>It’s not a good practice to do so and it may lead to unexpected bugs. <br><a href="https://coderwall.com/p/wrxwog/why-not-to-commit-pyc-files-into-git-and-how-to-fix-if-you-already-did">Why</a>?</p><p>This enticed me to look at what else I was not required to commit to git, and I discovered the website —<a href="http://gitignore.io/"><strong>gitignore.io</strong></a><strong>. </strong>The website provides one with the .gitgnore files of all(almost) programming languages and frameworks. <br>You can find the one for Django <a href="http://gitignore.io/api/django">here</a>.</p><p>I have been using<strong> </strong><a href="http://gitignore.io/"><strong>gitignore.io</strong></a><strong> </strong>since then for all of my projects.</p><p>My first Django application was <a href="http://spojscore.herokuapp.com/">Spoj Score</a>. It was also the first application that I deployed on <a href="https://heroku.com/">Heroku</a>. I also wrote an <a href="https://medium.com/free-code-camp/scheduling-jobs-in-a-django-application-using-heroku-scheduler-13c971a22979">article</a> about it.</p><p>I followed <a href="https://simpleisbetterthancomplex.com/tutorial/2016/08/09/how-to-deploy-django-applications-on-heroku.html">this</a> article on deploying a Django application on <a href="https://heroku.com/">Heroku</a>. The article introduced me to the requirement of requirements.txt — a text file containing the names(and versions) of all the Python packages required by the particular project, and to another useful package — dj_database_url.</p><p>requirements.txt is not only required when the application is to be deployed to Heroku. Suppose your friend wants to run your application on their computer. How would they know which packages to install to successfully run the application? Instead of leaving them scratching their head, it’s better to provide requirements.txt! Right?</p><p>The aforementioned article(<a href="https://simpleisbetterthancomplex.com/tutorial/2016/08/09/how-to-deploy-django-applications-on-heroku.html">this</a>) also mentions a bit about Procfile. Heroku apps include a Procfile that specifies the commands that are executed by the app on startup. You can read more about them <a href="https://devcenter.heroku.com/articles/procfile">here</a>.</p><p>Since I deploy most of my applications on Heroku, I started including requirements.txt, a Procfile, and runtime.txt in each of my projects. Yeah, the package dj_database_url too!</p><p>In simple words, dj_database_url allows us to receive the database parameters from the environment (using python-decouple?) as a single variable. The package’s <a href="https://github.com/jacobian/dj-database-url">README</a> is more than enough to get started. Have a read!</p><p>So, now, the initial project structure became —</p><pre>notes/<br>├── notes/<br>│   ├── settings.py<br>│   ├── urls.py<br>│   ├── wsgi.py<br>│   └── __init__.py<br>├── .env<br>├── .env.example<br>├── .gitignore<br><strong>├── requirements.txt<br>├── Procfile<br>├── runtime.txt</strong><br>└── manage.py</pre><p>A consistent addition that has found a place in all of my projects till now is the customization of Django’s User model. You all agree, right?</p><p>There are several ways to customize/extend the User model provided by Django. They have been elegantly described <a href="https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html">here</a>.</p><p>I prefer to create a custom user model extending AbstractUser(option 4 in the aforementioned article).</p><p>As I mentioned earlier, since this has been a consistent addition, it makes sense to start the project with an accounts app containing the custom user model.</p><p>So, now, the initial project structure becomes —</p><pre>notes/<br><strong>├── accounts/<br>│   ├── admin.py<br>│   ├── apps.py <br>│   ├── models.py<br>│   ├── tests.py<br>│   ├── urls.py<br>│   ├── view.py<br>│   └── __init__.py</strong><br>├── notes/<br>│   ├── settings.py<br>│   ├── urls.py<br>│   ├── wsgi.py<br>│   └── __init__.py<br>├── .env<br>├── .env.example<br>├── .gitignore<br>├── requirements.txt<br>├── Procfile<br>├── runtime.txt<br>└── manage.py</pre><p>As I proceeded further, I came to realize that there are project settings that are different for different environments.</p><p>Consider the settings pertaining to emails. They are different for development and production, in almost all cases. <br>I use(d) django.core.mail.backends.console.EmailBackend as the EMAIL_BACKEND during development and django.core.mail.backends.smtp.EmailBackend during production.</p><p>A quick Google search led me to <a href="https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html">this</a> fine article. Go through it before proceeding.</p><p>I disintegrate my settings into three different modules within a settings package—</p><ol><li>base.py — for settings common to both the development and production environment.</li><li>development.py — for settings unique to the development environment.</li><li>production.py — for settings unique to the production environment.</li></ol><p>So, now, the initial project structure becomes —</p><pre>notes/<br>├── accounts/<br>│   ├── admin.py<br>│   ├── apps.py <br>|   ├── models.py<br>|   ├── tests.py<br>│   ├── urls.py<br>|   ├── view.py<br>│   └── __init__.py<br>├── notes/<br><strong>│   ├── settings/<br>│   │  ├── base.py<br>│   │  ├── development.py<br>│   │  ├── production.py<br>│   │  └── __init__.py</strong><br>│   ├── wsgi.py<br>│   ├── urls.py<br>│   ├── <strong>wsgi.py             </strong><br>│   └── __init__.py<br>├── .env<br>├── .env.example<br>├── .gitignore<br>├── requirements.txt<br>├── Procfile<br>├── runtime.txt<br>└── <strong>manage.py</strong></pre><p>Wait.<br>Stop.<br>I forgot to write about virtual environments.</p><p>Well, you must be familiar with them as almost every article on an introduction to Django will mention it.</p><p>Not heard of it? <a href="https://docs.python.org/3/tutorial/venv.html">This</a> article will help then.</p><p>Developers tend to have their own preferences regarding the name and place of the virtual environment directory.</p><p>I, personally, am more comfortable with the following approach —</p><ol><li>Create a directory with the name of the project, and cd into it — <br>mkdir notes followed by cd notes. <br>This directory will contain the virtual environment and the project folder.</li><li>Create a virtual environment with the name venv, and use this as the project’s virtual environment.</li></ol><p>So, now, the project structure becomes —</p><pre><strong>notes/</strong><br>├── notes/<br>|   ├── accounts/<br>|   │   ├── admin.py<br>|   │   ├── apps.py <br>|   |   ├── models.py<br>|   |   ├── tests.py<br>│   |   ├── urls.py<br>|   |   ├── view.py<br>|   │   └── __init__.py<br>|   ├── notes/<br><strong>│   </strong>|   <strong>├── </strong>settings/<br>│   |   │  ├── base.py<br>│   |   │  ├── development.py<br>│   |   │  ├── production.py<br>│   |   │  └── __init__.py<br>│   |   ├── wsgi.py<br>│   |   ├── urls.py<br>│   |   ├── wsgi.py<br>│   |   └── __init__.py<br>|   ├── .env<br>|   ├── .env.example<br>|   ├── .gitignore<br>|   ├── requirements.txt<br>|   ├── Procfile<br>|   ├── runtime.txt<br>|   └── manage.py<br><strong>└── venv/<br>    ├── bin/<br>    ├── include/<br>    └── lib/</strong></pre><p>As of now, I tend to decide on logging and caching based on the project on hand. <a href="https://www.webforefront.com/django/setupdjangologging.html">This</a> article explains logging in Django beautifully. You can also find a lot about <a href="https://docs.djangoproject.com/en/dev/topics/logging/">logging</a> and <a href="https://docs.djangoproject.com/en/dev/topics/cache/">caching</a> in Django in the official documentation.</p><p>A good logging and caching implementation are very important for a project of any scale. Tend to include them in every project of yours!</p><p>At this point, I would also like to mention <a href="https://github.com/mailhog/MailHog">MailHog</a> as I, more than often, find myself using it.</p><p>During development, instead of receiving and viewing emails in the console, it’s possible to view them in a web UI (just like you view them in your Gmail inbox!). <a href="https://github.com/mailhog/MailHog">MailHog</a> allows us to do so. And that too, without any extra installation! Interesting, right? Instructions on how to use MailHog with Django can be found <a href="https://medium.com/@alfarhanzahedi/using-mailhog-with-django-c2dd54980a3d">here</a>.</p><p>This is not much of an important change, but I prefer to keep all the apps of a project within an apps directory. I also keep a templates and a static directory in the project root. These two directories contain the templates and static files that are shared by all the various different apps of the project.</p><p>So, the final project structure is —</p><pre>notes/<br>├── notes/<br>|   ├── <strong>apps/<br></strong>|<strong>   </strong>|<strong>   </strong>└── accounts/<br>|   |       ├── admin.py<br>|   |       ├── apps.py <br>|   |       ├── models.py<br>|   |       ├── tests.py<br>|   │       ├── urls.py<br>|   |       ├── view.py<br>|   |       └── __init__.py<br>|   |<br>|   ├── notes/<br><strong>│   </strong>|   <strong>├── </strong>settings/<br>│   |   │  ├── base.py<br>│   |   │  ├── development.py<br>│   |   │  ├── production.py<br>│   |   │  └── __init__.py<br>│   |   ├── wsgi.py<br>│   |   ├── urls.py<br>│   |   ├── wsgi.py<br>│   |   └── __init__.py<br>|   ├── .env<br>|   ├── .env.example<br>|   ├── .gitignore<br>|   ├── requirements.txt<br>|   ├── Procfile<br>|   ├── runtime.txt<br>|   ├── manage.py<br><strong>│   </strong><strong>├── static/                        <br>│   │   ├── css/<br>│   │   ├── img/<br>│   │   └── js/<br>│   └── templates/</strong><br>└── venv/<br>    ├── bin/<br>    ├── include/<br>    └── lib/</pre><p>I have compiled all of the above as a Django project template. You can find it <a href="https://github.com/alfarhanzahedi/django-project-template">here</a>. Peruse through the code. <br>You can also use it if you want! The README contains instructions on how to use the template.</p><p>That’s it, I guess.</p><p>Bye.</p><h4>Some Music Recommendations!</h4><p>During the last few weeks, I came across Latvian, Faroese and Russian folk songs on YouTube. And, they were, much to my surprise, just beautiful!</p><p>Many, many thanks to the YouTube recommendation system.</p><p>Here, check out some of them for yourselves —</p><ul><li><a href="https://www.youtube.com/watch?v=x3ntgZ3aZG4">Tautumeitas — Dai Citas Meitas</a></li><li><a href="https://www.youtube.com/watch?v=TzHljowYNvc">Tautumeitas — Sēdēja muoseņa</a></li><li><a href="https://www.youtube.com/watch?v=LsgO5OTUsRU">Tautumeitas — Raganu Nakts</a></li><li><a href="https://www.youtube.com/watch?v=NOsFQ-VUeMw">Eivør Pálsdóttir — Trøllabundin</a></li></ul><p>Yeah, I also do not understand the lyrics a bit (without English captions)! But, somehow they all sound and feel so good to me. Isn’t this what music is all about?</p><p>Have some recommendations for me? Comment them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dfcf505cb2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using MailHog with Django]]></title>
            <link>https://medium.com/@alfarhanzahedi/using-mailhog-with-django-c2dd54980a3d?source=rss-9a7400cae3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2dd54980a3d</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[mailhog]]></category>
            <dc:creator><![CDATA[Alfarhan Zahedi]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 14:27:15 GMT</pubDate>
            <atom:updated>2020-02-01T14:27:15.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E03TCY2FUB0jHyg8.png" /><figcaption><a href="https://www.djangoproject.com/s/img/logos/django-logo-negative.png">https://www.djangoproject.com/s/img/logos/django-logo-negative.png</a></figcaption></figure><p>What do you use as the EMAIL_BACKEND in Django during development?</p><p>I use django.core.mail.backends.console.EmailBackend. But, in some cases, it turns out to be not good enough. For example, consider the situations where we would want to test the UI aspects of the emails?</p><p>So, one fine day, while searching for alternative options, I came across <strong>MailHog</strong>.</p><p>In this short article, I am going to introduce you to <strong>MailHog</strong> and how to use it with Django.</p><p>In brief, <strong>MailHog</strong> is an email testing tool for developers that allows us to view emails in a web UI, or retrieve them via a JSON API.</p><p>So, using MailHog during development, you would be receiving emails in a web UI —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQv_U-yewWSDVQHOztKw-A.png" /><figcaption>MailHog’s web UI</figcaption></figure><p>You can find the official code repository of MailHog <a href="https://github.com/mailhog/MailHog">here</a> at GitHub. The README offers more insight on it’s features and usage.</p><p>Now, how to use MailHog with Django? Just three simple steps —</p><ul><li>Download the latest release of MailHog for your platform from <a href="https://github.com/mailhog/MailHog/releases/">here</a>. It’s v1.0.0 at the time of writing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*oW0M8oxRE3oZQzaBmOI1dg.png" /><figcaption>I downloaded MailHog_linux_amd64 since I use Ubuntu. If you use Windows, you should download either MailHog_windows_386.exe (32-bit) or MailHog_windows_amd64.exe (64-bit).</figcaption></figure><ul><li>Execute the downloaded file. <br>In Linux, you would need to traverse to the directory where you downloaded the executable — MailHog_linux_amd64(64-bit) or MailHog_linux_386(32-bit) and use the command — <br>./MailHog_linux_amd64 <br>or <br>./MailHog_linux_386 <br>to execute. In either case, you would get an output similar to this —</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*g_slIoIWThpPNrriBkGvJQ.png" /><figcaption>As evident from the output, we have started a SMTP server which is bound to the address — 0.0.0.0:1025 and a HTTP server which is bound to the address — 0.0.0.0:8025.</figcaption></figure><ul><li>Add/update the following lines in your project’s settings.py —</li></ul><pre>EMAIL_BACKEND = &#39;django.core.mail.backends.smtp.EmailBackend&#39;<br>EMAIL_HOST = 127.0.0.1<br>EMAIL_PORT = 1025</pre><p>Please note that you should fetch settings parameters from the environment instead of hard-coding them. You can read more about it <a href="https://simpleisbetterthancomplex.com/2015/11/26/package-of-the-week-python-decouple.html">here</a>. <br>I hard-coded them in order to make the changes required easier to understand.</p><p>After making the changes, all the emails sent will be available in a web UI at <a href="https://127.0.0.1:8025/">https://127.0.0.1:8025</a>. Try yourself!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQv_U-yewWSDVQHOztKw-A.png" /><figcaption>MailHog’s web UI (available at <a href="https://127.0.0.1:8025)">https://127.0.0.1:8025)</a></figcaption></figure><p>That’s it.</p><h3>Endnotes:</h3><ul><li>If you are unable to execute the downloaded binary (on Linux platform), it’s possible that you do not have execute permission over the binary. Provide yourself with the permission to execute the binary via the command — <br>chmod u+x MailHog_linux_amd64.</li><li>Some alternatives to MailHog include <a href="https://mailcatcher.me/">MailCatcher</a> and <a href="https://mailtrap.io/">Mailtrap</a>. Their usage with Django will, most probably, be the same as described in this article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2dd54980a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing ModelMultipleChoiceField in a Django Form]]></title>
            <link>https://medium.com/@alfarhanzahedi/customizing-modelmultiplechoicefield-in-a-django-form-96e3ae7e1a07?source=rss-9a7400cae3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e3ae7e1a07</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Alfarhan Zahedi]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 15:44:58 GMT</pubDate>
            <atom:updated>2018-11-09T15:44:58.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVKOLLX7wprRbHTl2IPDcQ.png" /><figcaption><a href="https://www.djangoproject.com/s/img/logos/django-logo-negative.png">https://www.djangoproject.com/s/img/logos/django-logo-negative.png</a></figcaption></figure><p><strong>Buckle Up! A ton of articles on Django on the way!</strong></p><p>And all thanks goes to the <strong>CodeChef API Hackathon</strong>.</p><p>You can learn more about it <a href="https://www.codechef.com/CAH1801">here</a>.</p><p>For the lazy ones (who are not willing to open the link and go through it), <a href="https://www.codechef.com/"><strong>CodeChef</strong></a><strong> </strong>in association with <a href="https://www.alibabacloud.com/"><strong>Alibaba Cloud</strong></a> organized a hackathon titled <strong>CodeChef API Hackthon</strong> where the participants(or teams) were given access to CodeChef’s API and vouchers for Alibaba Cloud Services. <br>In return, the participants (or teams) were asked to submit a ‘hack’ or a feature that <a href="https://www.codechef.com/"><strong>CodeChef</strong></a> was missing.</p><p>The contest lasted for over a month.</p><p>Our ‘hack’ was a web application based on Django. So, as you can guess, I got to know a <strong>LOT</strong> about Django, and thereby, I am going to share the gained knowledge with you all.</p><p>So, let us begin!</p><p>A part of our ‘hack’ was to provide the users with the option to create custom problem-sets by selecting problems from a list of problems.</p><p>We had a Problem model and the instances of this model would comprise the above mentioned list of problems.</p><pre><strong>class Problem(models.Model):    <br></strong>    &#39;&#39;&#39;        <br>    <em>code: code of the problems, ex - CCOOK        <br>    name: name of the problem, ex - &#39;Small Factorials&#39;        <br>    author: author of the problem        <br>    contest_code: code of the contest from which the problem is   <br>    taken contest_name: name of the above contest            <br>    contest_successful_submissions: number of successful submissions  <br>                   made for that specific problem during the contest          <br>    contest_accuracy: accuracy of the submissions made        <br>    tags: tags associated with the problem, ex - &#39;dp, easy, strings&#39;          <br>    </em>&#39;&#39;&#39;    <br>    code = models.CharField(max_length = 16, unique = True)    <br>    name = models.CharField(max_length = 64)    <br>    author = models.CharField(max_length = 64)    <br>    contest_code = models.CharField(max_length = 16)    <br>    contest_name = models.CharField(max_length = 64)        <br>    contest_successful_submissions = models.IntegerField()     <br>    contest_accuracy = models.FloatField()    <br>    tags = models.CharField(max_length = 256)     <br>    <br><strong>    class Meta:        <br></strong>        ordering = [&#39;-contest_successful_submissions&#39;]     <br>    <br>    <strong>def</strong> __str__(self):        <br>        <strong>return</strong> f&#39;{self.name} ({self.code})&#39;</pre><p>Duh! It’s easy.</p><p>Just add a ModelMultipleChoiceField with queryset = Problem.objects.all() to the appropriate form class, and you’re golden.</p><p>In my case, the form class would have been:</p><pre><strong>class CustomSetForm(forms.ModelForm):<br></strong>    title = forms.CharField(max_length = 32)<br>    description = forms.CharField(max_length = 256)</pre><pre>    duration = forms.CharField(widget = forms.TextInput(attrs =   <br>                        {&#39;min&#39;: 20,&#39;max&#39;: 300,&#39;type&#39;: &#39;number&#39;}))</pre><pre>    problems = forms.ModelMultipleChoiceField(<br>                       widget = forms.CheckboxSelectMultiple,<br>                       queryset = Problem.objects.all()<br>               )</pre><p>As one can predict, on rendering this form, the problems will appear as list of checkboxes where the ‘text’ for each problem (or checkbox) will be same as that returned by the__str__() function defined inside the Problem model (see above).</p><p>As a result, we will get something as the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ytsOSyDuDjikVvdtu0SEpQ.png" /></figure><p>But this is not what we wanted. We wanted to show all the details of a problem (i.e. all the fields of the Problem model), along with the possibility of styling those different fields(of the Problem model) differently.</p><p>We wanted (and achieved) something as the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*0ZYFHhpf53TpBCYGHWo7Yw.png" /></figure><p>See?</p><p>We were unable to achieve this by simply tweaking the __str__() function.</p><p>So, how did we do it?</p><p>It’s simple. We just defined our own classes inheriting models.ModelChoiceIterator, and models.ModelMultipleChoiceField.</p><p>Let’s dive into the details of the solution or ‘hack’ now.</p><p>The ModelChoiceIterator class is used as an iterator by ModelChoiceField, and in turn by ModelMultipleChoiceField. You can view the source code <a href="https://docs.djangoproject.com/en/2.1/_modules/django/forms/models/">here</a>.</p><p>What interests us is the choice function inside the ModelChoiceIterator class.</p><pre><strong>class</strong> <strong>ModelChoiceIterator</strong>:<br>   .<br>   .<br>   .<br>   .<br>   <strong>def</strong> choice(self, obj):<br>        <strong>return</strong> (self.field.prepare_value(obj), <br>                self.field.label_from_instance(obj))</pre><p>As you can see, choice(self, obj) returns a tuple with two elements - value and label for each of the choice field, which is used in the template while rendering the form.</p><p>To get all the fields of the instances of Problem available during the rendering of the form, we defined a new iterator — CustomModelChoiceIterator(inheriting models.ModelChoiceIterator), in which we redefined choice(self, obj) and made it return a tuple with three elements, the third element being obj itself.</p><pre><strong>class CustomModelChoiceIterator(models.ModelChoiceIterator):<br></strong>    <strong>def</strong> choice(self, obj):<br>        <strong>return</strong> (self.field.prepare_value(obj),<br>                self.field.label_from_instance(obj), <strong>obj</strong>)</pre><p>Now, we can access and display all the fields of an instance of Problem via obj.</p><p>Next, we defined the class — CustomModelChoiceField(inheriting models.ModelMultipleChoiceField), in which we redefined _get_choices(self) to use CustomModelChoiceIterator(defined above) as the iterator instead of ModelChoiceIterator.</p><pre><strong>class CustomModelChoiceField(models.ModelMultipleChoiceField):<br>    def</strong> _get_choices(self):<br>        if hasattr(self, &#39;_choices&#39;):<br>            return self._choices<br>        <strong>return</strong> CustomModelChoiceIterator(self)</pre><pre>    choices = property(_get_choices,  <br>                       MultipleChoiceField._set_choices)</pre><p>After defining the above two classes (the two classes should be in the same file as the form class i.e. the same forms.py), we incorporated them in our form and rendered the form in our template like a boss 😎.</p><p>Here’s a part of the form class using the CustomModelChoiceField:</p><pre><strong>class CustomSetForm(forms.ModelForm):<br></strong>    title = forms.CharField(max_length = 32)<br>    description = forms.CharField(max_length = 256)</pre><pre>    duration = forms.CharField(widget = forms.TextInput(attrs =   <br>                        {&#39;min&#39;: 20,&#39;max&#39;: 300,&#39;type&#39;: &#39;number&#39;}))</pre><pre>    problems = <strong>CustomModelChoiceField</strong>(<br>                       widget = forms.CheckboxSelectMultiple,<br>                       queryset = Problem.objects.all()<br>               ) <br>    .<br>    .<br>    .<br>    .</pre><p>Here’s part of the template where we render the problems field of CustomSetForm.</p><pre>&lt;div class=&quot;row&quot;&gt;<br><strong>{% for value, label, problem in form.problems.field.choices %}<br></strong> &lt;div class=&quot;col-lg-6 col-md-6 col-sm-12 col-xs-12&quot;&gt;<br>  &lt;li&gt;<br>   &lt;label class=&quot;checkbox-label-container&quot;&gt;<br>    &lt;input type=&quot;checkbox&quot; value=&quot;{{ value }}&quot; name=&quot;problems&quot;&gt;<br>    &lt;span class=&quot;checkmark&quot;&gt;&lt;/span&gt;<br>    &lt;a href=&quot;https://codechef.com/problems/{{problem.code}}&quot; <br>    target=&quot;_blank&quot;&gt;<br>     &lt;b&gt;{{ problem.name }}&lt;/b&gt;<br>     &lt;span id=&quot;problem-{{ value }}&quot;&gt;({{ problem.code }})&lt;/span&gt;<br>    &lt;/a&gt;<br>    &lt;br/&gt;<br>    &lt;span&gt;{{ problem.contest_name }}&lt;/span&gt;<br>    &lt;br/&gt;<br>    &lt;span&gt;Successful submissions (in contest): <br>    {{ problem.contest_successful_submissions }}&lt;/span&gt;<br>    &lt;br/&gt;<br>    &lt;span&gt;Tags: {{ problem.tags|load_list_items }}&lt;/span&gt;<br>   &lt;/label&gt;<br>  &lt;/li&gt;<br> &lt;/div&gt;<br><strong> {% endfor %}<br></strong>&lt;/div&gt;</pre><p>Since, choice(self, obj) returns a tuple with three elements instead of two, we use three variables — value, label, and problem, in the for loop, to store the three elements of the returned tuple.</p><p>Recall that the third element was obj itself. Hence, we are able to access all the fields of an instance of Problem via the problem variable in the template.</p><p>That’s it. Done.</p><p>Our complete forms.py (which can be used as a reference) can be found <a href="https://github.com/alfarhanzahedi/chefsarena/blob/master/core/forms.py">here</a>.<br>The corresponding template’s code can be found <a href="https://github.com/alfarhanzahedi/chefsarena/blob/master/core/templates/core/create_practice_custom_form.html">here</a>.</p><h3>Endnotes:</h3><p>If you are interested, you can find our ‘hack’ or web application here — <a href="http://149.129.138.147/">http://149.129.138.147/</a>.</p><p>Any form feedback will be appreciated 😄.</p><p>I stumbled across some interesting and useful articles during the last few weeks. Here’s some of them —</p><ol><li><a href="https://css-tricks.com/the-complete-guide-to-lazy-loading-images/">The Complete Guide to Lazy Loading Images</a> — annoyingly beautiful post on lazy loading images. Highly recommended. A must read!</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Layout_cookbook">CSS Layout Cookbook</a>.</li><li><a href="https://medium.com/datadriveninvestor/stopping-using-console-log-and-start-using-your-browsers-debugger-62bc893d93ff?mc_cid=5d0d3ab15d&amp;mc_eid=396c1e39eb">How to stop using console.log() and start using your browser’s debugger</a>.</li><li><a href="https://medium.com/samsung-internet-dev/are-you-accessible-a-primer-on-web-accessibility-7b2ab0ceffe8">👉 Are you accessible? 👈 — A Primer on Web Accessibility</a>.</li></ol><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e3ae7e1a07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to schedule jobs in a Django application using Heroku Scheduler]]></title>
            <link>https://medium.com/free-code-camp/scheduling-jobs-in-a-django-application-using-heroku-scheduler-13c971a22979?source=rss-9a7400cae3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c971a22979</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Alfarhan Zahedi]]></dc:creator>
            <pubDate>Tue, 05 Jun 2018 07:59:00 GMT</pubDate>
            <atom:updated>2019-05-07T15:35:52.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6htRSu-GZiU0wo_uStebQ.jpeg" /><figcaption><a href="https://unsplash.com/@agebarros">https://unsplash.com/@agebarros</a></figcaption></figure><p>Recently, I published my first Django application on Heroku.</p><p>The application is fairly simple — it lists the score associated with every <strong>classical</strong> problem on <a href="http://www.spoj.com/">SPOJ</a>.</p><blockquote><a href="http://www.spoj.com/"><strong>SPOJ</strong></a> — Sphere Online Judge — is a problemset archive, online judge and contest hosting service accepting solutions in many languages.</blockquote><p>You can find the application live <a href="https://spojscore.herokuapp.com/">here</a>.</p><p>The application uses the Python libraries <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">bs4</a> and <a href="http://docs.python-requests.org/en/master/">requests</a> to scrape the contents of the aforementioned website, obtain the required details for every problem (namely — problem code, problem name, users and <strong>score</strong>), and store them in a database.</p><p>Now, the score associated with the problems on <a href="http://spoj.com/">SPOJ</a> is dynamic. It is calculated using the following formula:</p><p>80 / (40 + number_of_people_who_have_solved_the_problem)</p><p>So, the score associated with the problems on <a href="http://spoj.com/">SPOJ</a> changes as number_of_people_who_have_solved_the_problem<em> </em>changes.</p><p>Hence, the data collected by my application will be rendered useless after a certain interval of time. I need to set up a scheduler to keep my database updated.</p><p>Now, it’s a dead simple application. So I wanted to set up the scheduler with the least amount of configuration and code possible.</p><h3><em>Custom Django Management Commands and Heroku Scheduler to the rescue!</em></h3><p>Let us understand our two saviors.</p><h4>1. Custom Django Management Commands</h4><p>Custom Django Management Commands are structured as Python classes that inherit their properties and behavior from django.core.management.base.BaseCommand class.</p><p>They are used to add a manage.py action for a Django app. runserver or migrate are two such actions.</p><p>A typical example of such a class would be:</p><pre>from django.core.management.base import BaseCommand</pre><pre><strong>class</strong> <strong>Command</strong>(BaseCommand):<br>    help = &quot;&lt;appropriate help text here&gt;&quot;<br>    <strong>def</strong> handle(self, *args, **options):<br>        self.stdout.write(&quot;Hello, World!&quot;)</pre><p>The class must be named Command, and subclass BaseCommand.</p><p>help should hold a short description of the command, which will be printed in help messages.</p><p>handle(self, *args, **options) defines the actual logic of the command. In this case, we are just writing the string Hello, World! into the standard output. In my case, handle(self, *args, **options) performs the task of scraping the website — <a href="http://spoj.com/">spoj.com</a> and updating the database if the <strong>score </strong>associated with any of the problem changes.</p><p>handle(self, *args, **options) is automatically run whenever the following command is used:</p><p>python manage.py &lt;name of the python script containing the management class&gt;</p><p>If the name of the script is, say, script.py, then the command would be:</p><p>python manage.py script</p><p>Notice the handle method declares three input argument: self to reference the class instance, *args to reference arguments of the method itself, and **option to reference arguments passed as part of the management command.</p><p><strong>Where in the project structure does this </strong><strong>script.py go?</strong></p><p>(Here, script.py refers to the name of the script containing the custom Django management command.)</p><p>It’s quite simple. The <a href="https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/">official documentation</a> explains it well:</p><blockquote><em>Just add a </em><strong><em>management/commands</em></strong><em> directory to the application. Django will register a </em><strong><em>manage.py</em></strong><em> command for each Python module in that directory whose name doesn’t begin with an underscore.</em></blockquote><blockquote><em>For example:</em></blockquote><pre>polls/<br>    __init__.py<br>    models.py<br>    management/<br>        __init__.py<br>        commands/<br>            __init__.py<br>            _private.py<br>            closepoll.py<br>    tests.py<br>    views.py</pre><blockquote><em>In this example, the </em><strong><em>closepoll</em></strong><em> command will be made available to any project that includes the </em><strong><em>polls</em></strong><em> application in </em><a href="https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-INSTALLED_APPS"><strong><em>INSTALLED_APPS</em></strong></a><em>.</em></blockquote><blockquote><em>The </em><strong><em>_private.py</em></strong><em> module will not be available as a management command.</em></blockquote><blockquote><em>The </em><strong><em>closepoll.py</em></strong><em> module has only one requirement – it must define a class </em><strong><em>Command</em></strong><em> that extends </em><a href="https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/#django.core.management.BaseCommand"><strong><em>BaseCommand</em></strong></a><em> or one of its </em><a href="https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/#ref-basecommand-subclasses"><em>subclasses</em></a><em>.</em></blockquote><blockquote><em>And so, if we run the following command in our terminal:</em></blockquote><blockquote><em>python manage.py closepoll ,</em></blockquote><blockquote><em>handle(self, *args, **options) inside </em><em>closepoll.py will be run, and any logic/tasks contained inside the aforementioned function will be executed.</em></blockquote><p>My project structure is as follows:</p><pre>spojscore<br>│   .gitignore<br>│   manage.py<br>│   Procfile<br>│   README.md<br>│   requirements.txt<br>│   runtime.txt<br>│<br>├───core<br>│   │   admin.py<br>│   │   apps.py<br>│   │   models.py<br>│   │   tests.py<br>│   │   views.py<br>│   │   __init__.py<br>│   │<br>│   ├───management<br>│   │   │   __init__.py<br>│   │   │<br>│   │   ├───commands<br>│   │         script.py<br>│   │         __init__.py<br>│   │     <br>│   │<br>│   ├───static<br>│   │   └───core<br>│   │       ├───css<br>│   │       │       style.css<br>│   │       │<br>│   │       └───img<br>│   │               favicon.png<br>│   │               logo.png<br>│   │<br>│   ├───templates<br>│       └───core<br>│               core.html<br>│<br>└───spojscore<br>        settings.py<br>        urls.py<br>        wsgi.py<br>        __init__.py<br></pre><p>Here, script.py contains the custom management command — Python code to scrape <a href="http://spoj.com/">spoj.com</a>, collect details of all the <strong>classical</strong><em> </em>problems, and update the database accordingly.</p><p>If you see, it’s situated inside core\management\commands.</p><p>If you are interested, you can find script.py <a href="https://github.com/alfarhanzahedi/spojscore/blob/master/core/management/commands/script.py">here</a>.</p><p>I think its clear now that I can scrape spoj.com and obtain the desired data by simply running python manage.py script from the terminal.</p><p>So, to keep my database updated, I just need to run the above command at least once a day.</p><h4>2. Heroku Scheduler</h4><p>As per <a href="https://devcenter.heroku.com/articles/scheduler">Heroku’s website</a>:</p><blockquote><a href="https://elements.heroku.com/addons/scheduler"><em>Scheduler</em></a><em> is a free </em><a href="https://elements.heroku.com/addons"><em>add-on</em></a><em> for running jobs on your app at </em><a href="https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes"><em>scheduled time intervals</em></a><em>, much like </em><em>cron in a traditional server environment.</em></blockquote><blockquote><em>A dashboard allows you to configure jobs to run every 10 minutes, every hour, or every day, at a specified time. When invoked, these jobs will run as </em><a href="https://devcenter.heroku.com/articles/one-off-dynos"><em>one-off dynos</em></a><em> and show up in your logs as a dyno named like </em><em>scheduler.X.</em></blockquote><p>Once you’ve deploying the application, install the Heroku Scheduler add-on.</p><p>To schedule a frequency and time for a job, open the Heroku Scheduler dashboard by finding the app in <a href="https://dashboard.heroku.com/apps">My Apps</a>, clicking “Overview”, then selecting “Heroku Scheduler” from the Installed add-ons list.</p><p>On the Scheduler Dashboard, click “Add Job…”, enter a task, select a frequency, <a href="https://devcenter.heroku.com/articles/dyno-types">dyno size</a>, and next run time.</p><p>In my case, the task is python manage.py script, which is to be executed daily (frequency) using my free dynos (dyno size) at 00:00 UTC (next run time).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*ikLMpHEvVyEf7zS49rHb3g.png" /></figure><p>That’s it!</p><p>My database will be updated at 00:00 UTC every day, and I didn’t have to install any extra Python libraries, or write any extra pieces of code. Yay!</p><p>If you get stuck anywhere, drop a comment and I will try my best to help you.</p><h3>Some final notes:</h3><ul><li><a href="https://devcenter.heroku.com/articles/scheduler">Heroku’s official website</a> says that — <em>“Scheduler job execution is expected but not guaranteed. Scheduler is known to occasionally (but rarely) miss the execution of scheduled jobs. If scheduled jobs are a critical component of your application, </em><strong><em>it is recommended to</em></strong><em> </em><a href="https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes"><strong><em>run a custom clock process</em></strong></a><em> instead for more reliability, control, and visibility.”</em> This point should be kept in mind while using Heroku Scheduler. <br>Mine is dead simple application which uses the Heroku Scheduler to run a simple script just once a day. So, I guess it would do a great job!</li><li>My application, I suppose, is useful for competitive programmers. Why? I have explained it in great detail <a href="https://discuss.codechef.com/questions/113220/value-points-of-spoj-problems">here</a>.</li><li>You can find the source code of my application <a href="https://github.com/alfarhanzahedi/spojscore">here</a>.</li></ul><h3>A piece from my personal musings:</h3><p>I am just another self-taught programmer.</p><p>I have being writing code for a couple of years now, and have always wanted to write about my experiences, endeavors, failures and successes.</p><p>But alas, I could not.</p><p>I thought that my endeavors were not exciting enough or that my experiences were not going to help anyone. And so I restrained myself from writing about them.</p><p>To be honest, I think the same now.</p><p>So, how come I wrote this article?</p><p>Well, this is going to be my first of many articles.</p><p>And the reason for the change, you ask?</p><p>A newsletter.</p><p>Last week, as usual, I received the weekly newsletter from CSS-Tricks — <em>“This week in Web Design and Development”</em>.</p><p>Here, is an excerpt from the same:</p><blockquote>It’s buck wild to have so many helpful resources available to help us at any moment: from blog posts and books to random node.js conference talks that only have 8 views and 7 of them are now mine. So I think this weekend has reinforced my faith in blogging and sharing what you know, where random notes left on some developer’s old blog have helped me tremendously.</blockquote><blockquote>Anywho, on a similar note, I’ve been thinking a bunch about how social networks prioritize fame over value. If you publish something on Medium for example and it only gets a single clap then it makes you feel like, <em>why bother</em>? What’s the point if no-one’s reading this thing? But I think we have to fight that inclination to be woo’d with fame and social-network notoriety because I wonder how many helpful blog posts and videos weren’t made simply because someone thought they weren’t going to get half a million likes or retweets from it.</blockquote><blockquote>My advice after learning from so many helpful people this weekend is this: if you’re thinking of writing something that explains something you struggled with, do it! Don’t worry about the views and likes and Internet hugs. If you’ve struggled with figuring out this one weird thing then jot it down, even if it’s unedited and it uses too many commas and you don’t like the tone of it.</blockquote><blockquote>That’s because someone like me is bound to find what you’ve written and it’ll make their whole weekend a lot less stressful than it could’ve been.</blockquote><p>That’s it. Those few lines inspired me to write about my endeavors and experiences.</p><p><strong>Maybe, you should too.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c971a22979" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/scheduling-jobs-in-a-django-application-using-heroku-scheduler-13c971a22979">How to schedule jobs in a Django application using Heroku Scheduler</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>