<?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[Lemon Code - Medium]]></title>
        <description><![CDATA[For all of that extra juicy code snippets - Medium]]></description>
        <link>https://medium.com/lemon-code?source=rss----ffec8e390ec3---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Lemon Code - Medium</title>
            <link>https://medium.com/lemon-code?source=rss----ffec8e390ec3---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:04:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/lemon-code" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Expand admin’s interface filters usage to your front-end views — Django]]></title>
            <link>https://medium.com/lemon-code/adminfilters-27a2f7e0c19c?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/27a2f7e0c19c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dry]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 01:47:22 GMT</pubDate>
            <atom:updated>2020-05-02T22:35:18.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>Expand admin’s interface filters usage to your front-end views — Django</h3><h4>Provide filters to views by simply reusing previously created admin classes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JBWgVAhGjlE7YlTJ--vMA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@johnbogna?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Bogna</a>, snippet from <a href="https://carbon.now.sh/4yhTrBVQQJ0PbrRB2tZU">@carbon_app</a></figcaption></figure><p>Django admin filters are pretty awesome and using the SimpleListFilter expands on the basic filters over fields. Here’s a quick example just to remember how they work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6522d7dee9f338a1e2aeafcd850acdcb/href">https://medium.com/media/6522d7dee9f338a1e2aeafcd850acdcb/href</a></iframe><p>But did you know that we can do <em>much more </em>with them? How about using them in your views to provide filtering to your project outside of the Django admin interface?</p><p>A couple of simple changes are necessary for this to work properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da0dc5878cc45280e5867fccdc84c310/href">https://medium.com/media/da0dc5878cc45280e5867fccdc84c310/href</a></iframe><p>Start with your SimpleListFilter by moving your lookups to class method because we’ll need to get them without an instance of your class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca199e43a3da590bc5c22736af82d410/href">https://medium.com/media/ca199e43a3da590bc5c22736af82d410/href</a></iframe><p>This is related to a Form we must have which will dynamically create its own fields based on the filters provided to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e69b10d3a9689a8409fbdf5e167ed07/href">https://medium.com/media/7e69b10d3a9689a8409fbdf5e167ed07/href</a></iframe><p>Now, the view we want to apply the filters to must use that form and inherit from a mixin that can grab the filters from GET parameters and use them in a QuerySet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7552145a26badfacf5b285cbfb1655af/href">https://medium.com/media/7552145a26badfacf5b285cbfb1655af/href</a></iframe><p>Finally, by adding the form to our template and setting the submit method to GET, the form should be rendered properly and whenever it’s submitted, the results will be filtered according to the options chosen, like in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*2sI6jlb5EV7J9_nanZjV6w.gif" /><figcaption>It’s your job now to <em>make it fancy</em></figcaption></figure><p>This is a really simple example of filters. Personally I’ve added filters for relations with ForeignKeys, date ranges, years and months and more. I leave this challenge to you, but if you need any help leave a comment and I’ll try to answer it to my best knowledge 😄</p><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/icarovirtual/lemoncode/tree/master/adminfilters">icarovirtual/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a2f7e0c19c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/adminfilters-27a2f7e0c19c">Expand admin’s interface filters usage to your front-end views — Django</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A study on Django queries to improve admin load times]]></title>
            <link>https://medium.com/lemon-code/improve-admin-adcd46e51b71?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/adcd46e51b71</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 13:48:23 GMT</pubDate>
            <atom:updated>2021-07-15T15:00:49.742Z</atom:updated>
            <content:encoded><![CDATA[<h4>Aggregators can be a problem, let’s understand why and how to handle this situation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGwLrDuPKnkujyEvjTtyQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glm_murshed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Md. Golam Murshed</a>, snippet from <a href="https://carbon.now.sh/56ulrvv2O5f0Wlbv7Sro">@carbon_app</a></figcaption></figure><p>One of these days I noticed that after adding annotated columns to a model’s Manager the load time of its Django admin’s pages was slower than before.</p><p>To investigate what could be happening I used <a href="https://github.com/jazzband/django-debug-toolbar">Django Debug Toolbar</a> to take a look at the SQL being executed and got curious about this part of the result:</p><figure><img alt="Screen capture showing the query’s joins and information about similar queries being repeated." src="https://cdn-images-1.medium.com/max/736/1*oiUKNL21JQWTDWdBpv_npw.png" /><figcaption>This took 33% of the SQL load time</figcaption></figure><p>I am no pro<em> </em>at database management but I know that eachJOIN requires a lookup in another table which impacts the query execution and those in the image are there exactly because of the <a href="https://docs.djangoproject.com/en/2.2/ref/models/conditional-expressions/#case">Case</a> annotations I used (which normalize some data based on the model’s related fields values).</p><p>Also, we have a little message saying “2 similar queries. Duplicated 2 times.” which means that we end up using double the time for this operation because it’s repeated in some other function while the request is being processed.</p><p>From the Django Debug Toolbar panel, by expanding both “similar queries”, the source code trace shows that they are operations to count the page’s object lists hence why they are similar. One is for the quantity of items of each page at .../core/paginator.py:87 and the other is for the total quantity of items of all pages (result of the attribute show_full_result_count of ModelAdmin, which you could disable) at .../admin/views/main.py:213.</p><p>The source code mentioned above shows that these operations are pretty entangled in Django admin’s structure and optimizing them directly will require inheriting classes, overriding functions, copying their original content and tweaking the block which handles the QuerySet.</p><blockquote>My first insight was that <strong>annotations don’t change the quantity of elements of the queryset so their operations aren’t needed here</strong>, and I could work on a way to remove them before the <a href="https://docs.djangoproject.com/en/2.2/ref/models/querysets/#when-querysets-are-evaluated">queries are evaluated</a>.</blockquote><figure><img alt="Attempts to fiddle with the query trying to remove annotations" src="https://cdn-images-1.medium.com/max/816/1*D-8RnMmfJpjEdPd0Mbpfnw.png" /><figcaption>Read the docs, debug, inspect, etc., snippet from <a href="https://carbon.now.sh/WV8ixXDtymBSy8N661Ll">@carbon_app</a></figcaption></figure><p>After much fiddling with Queryset.query I managed to “<a href="https://stackoverflow.com/a/51873954/1245235">remove</a>” annotations but they mess with the query structure in the first place which made full optimization not possible by this approach…</p><p>Looking for other possibilities based on my initial premise, I thought:</p><ul><li>Annotations don’t modify the number of results so instead of removing them, they might not even be needed on the first place</li><li>What changes the number of results are the filters, so if it’s possible to copy them, it’s also possible to create a new QuerySet without annotations</li></ul><p>So I figured that queryset.model.objects.all() provides a QuerySet with no annotations and the filters could be re-applied by copying the attributes queryset.query.where and queryset.query.where_class from the original to the new QuerySet. Below is an implementation of this behavior:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0f5df667903903300ad54e6d66db75/href">https://medium.com/media/fa0f5df667903903300ad54e6d66db75/href</a></iframe><p>After applying this optimization (example is linked at the bottom of this story) a comparison can be made showing the achieved results in page loading times and queries being executed:</p><figure><img alt="Comparing execution time before and after optimization" src="https://cdn-images-1.medium.com/max/916/1*wRYZM8zA2TCoe1OouExP4Q.png" /><figcaption>Benchmarking over around 12k objects in the database</figcaption></figure><p>No JOIN, no problem. Without the annotations it takes only about 4% of the initial time and the SQL query is much simpler too, doing only the COUNT operation that is desired at these functions.</p><blockquote>Each query execution time went from ~140ms to ~7ms which is an improvement of around 190% on total page load time.</blockquote><p>The next step is to turn all of this into a mixin which will let ModelAdmin classes effortlessly inherit the optimization. For this, both ChangeList and Paginator base Django classes need to be extended and changed to include the copy_queryset_without_annotations function explained above and these new classes will be part of the the final mixin class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/624a09e313a79d6c71b911530fefb309/href">https://medium.com/media/624a09e313a79d6c71b911530fefb309/href</a></iframe><p>Please consider looking at the complete source code for this story that is linked below, which you can use in your projects and even contains a bonus improvement that uses <a href="https://docs.djangoproject.com/en/2.2/ref/models/querysets/#defer">Queryset.defer</a> to further decrease SQL overhead.</p><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/icarovirtual/lemoncode/tree/master/admin-optimizer">icarovirtual/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcd46e51b71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/improve-admin-adcd46e51b71">A study on Django queries to improve admin load times</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guard clauses for better “if” statements — Python]]></title>
            <link>https://medium.com/lemon-code/guard-clauses-3bc0cd96a2d3?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/3bc0cd96a2d3</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Sun, 11 Aug 2019 18:15:16 GMT</pubDate>
            <atom:updated>2019-08-31T13:01:44.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Guard clauses for better “if” statements — Python</h3><h4>Readability needs to be key when writing complex functions</h4><figure><img alt="Photo by Nery, snippet made in @carbon_app" src="https://cdn-images-1.medium.com/max/1024/1*tz4YmXY_EZW85MDynQsRhQ.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/eJ-vvwrO6IE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nery</a>, snippet from <a href="https://carbon.now.sh/cqL2xkLqnY882tVsPRCZ">@carbon_app</a></figcaption></figure><p>Lots of things can make code hard to understand. Confusing variables, high coupling, unnecessary complexity, and many other that we see (and sometimes do) everyday.</p><p>Sometimes we can’t avoid functions that need lots of validations to make sure it can execute what it’s there for. You can see an example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21de6b889b88f5ce9061de738652857c/href">https://medium.com/media/21de6b889b88f5ce9061de738652857c/href</a></iframe><p>That’s very simple but you can see that the nested if statements make a “stairs” effect in the code, increasing line width which can harm code readability and increase complexity (by having you need to “remember” all the previous conditions of each if).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12nDZFClQlLh4I%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12nDZFClQlLh4I%2Fgiphy.gif&amp;image=http%3A%2F%2Fgiphygifs.s3.amazonaws.com%2Fmedia%2F12nDZFClQlLh4I%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="329" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa8bca908868f488d9cf47925227968e/href">https://medium.com/media/fa8bca908868f488d9cf47925227968e/href</a></iframe><p>The <em>Guard Clause</em> pattern helps in these cases by “inverting” that way of thinking and rapidly returning false conditions and keeping the important code blocks (usually the longest) in the lowest indentation level possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/490bd4c07d59f858c21d2a0192c3addf/href">https://medium.com/media/490bd4c07d59f858c21d2a0192c3addf/href</a></iframe><p>We have increased the line count but it’s a valid trade-off for the code quality improvements that counter what we mentioned in the previous example.</p><p>Below is another example of before and after applying <em>guard clauses</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb4a962fe08f3c313a81b5eb2fee5b24/href">https://medium.com/media/cb4a962fe08f3c313a81b5eb2fee5b24/href</a></iframe><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/icarovirtual/lemoncode/tree/master/guard-clauses">icarovirtual/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc0cd96a2d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/guard-clauses-3bc0cd96a2d3">Guard clauses for better “if” statements — Python</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desktop notifications when your server reloads — Django]]></title>
            <link>https://medium.com/lemon-code/notify-2dbbc7bd48f0?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/2dbbc7bd48f0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Wed, 22 May 2019 16:23:25 GMT</pubDate>
            <atom:updated>2019-08-31T13:02:09.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Desktop notifications when your server reloads — Django</h3><h4>End your anxiety from staring at your terminal for too long</h4><figure><img alt="Photo by Mihai Surdu on Unsplash, snippet by @carbon_app" src="https://cdn-images-1.medium.com/max/1024/1*rZQIlKIWfQC_6LCLMu4gPg.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/AO9b7FN6ZLk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mihai</a>, snippet from <a href="https://carbon.now.sh/Hg58nyBnRCEjFilz79pZ">@carbon_app</a></figcaption></figure><p>Here’s a quickie. It can be annoying to keep looking at your terminal, waiting for your server to reload every time you make changes to your code, specially on bigger projects that it takes a handful of seconds for this process to finish.</p><p>If you are on Mac, I have a cool tip to improve this by using the <a href="https://github.com/setem/pync">pync</a> library that wraps the OS’s Notification Center.</p><p>The trick is to <a href="https://medium.com/lemon-code/monkey-patch-f1de778d61d3">monkey-patch</a> Django’s loading process and inject the notification code at the moment that the server is loaded and ready to go.</p><p>(I recommend you to do this is in your local.py file because this will ensure that you don’t impose it to your project’s peers 😉)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb1d002b1b22ca5c3140404fcb5d5ffa/href">https://medium.com/media/cb1d002b1b22ca5c3140404fcb5d5ffa/href</a></iframe><p>With this set up, every time Django says “System check identified no issues” a notification will pop in your screen (followed by a distinct sound) so you will know for sure that you can access your development server, reload the views you are testing or continue doing whatever you need to reload your server for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*jX4kINZdKHOiSCk8oBQyTg.png" /><figcaption>Close reddit and get back to work!</figcaption></figure><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/icarovirtual/lemoncode/tree/master/notify">icarovirtual/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dbbc7bd48f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/notify-2dbbc7bd48f0">Desktop notifications when your server reloads — Django</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple and clean way to monkey-patch your apps — Django]]></title>
            <link>https://medium.com/lemon-code/monkey-patch-f1de778d61d3?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/f1de778d61d3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 19:20:26 GMT</pubDate>
            <atom:updated>2020-04-23T01:39:58.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monkey-patch your apps in a simple and elegant manner — Django</h3><h4>Keep your patches locally and toggle them with ease</h4><figure><img alt="Photo by Edgar, snippet made in @carbon_app" src="https://cdn-images-1.medium.com/max/1024/1*Op5yszQrdaguFqMxF-RTKw.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/1CsaVdwfIew?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Edgar</a>, snippet from <a href="https://carbon.now.sh/wd3xMGEWhP3URaZtFh5s">@carbon_app</a></figcaption></figure><p>When we are testing one of our applications’ flows which consists of multiple steps that include filling forms (e.g., customer registers, fills product details and an administrator verifies the information in a classified ads platform) it can be quite repetitive to input every single field everytime.</p><p>One way to help with this is to fill the dictionary of the view’s get_initial method which will make your form already load with the needed data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/846f1a93e4ff9fc3de56accf74d4f575/href">https://medium.com/media/846f1a93e4ff9fc3de56accf74d4f575/href</a></iframe><p>This works but is <strong>not</strong> recommended since you are mixing actual code and logic with temporary stuff that can confuse you and even be problematic to others if added to your repository by mistake.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0HlHvq99kx8AGIxy%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsyfy-van-helsing-vanessa-l0HlHvq99kx8AGIxy&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0HlHvq99kx8AGIxy%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df5859be8ef81344ce1c267b15660d7/href">https://medium.com/media/5df5859be8ef81344ce1c267b15660d7/href</a></iframe><p>We can improve on this by using a technique called <a href="https://en.wikipedia.org/wiki/Monkey_patch">monkey-patching</a>. After making the adjustments, we have an isolated code block that can easily be removed or changed without interfering with the actual logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78646d2a3fb97fb5de4d63fbc5979595/href">https://medium.com/media/78646d2a3fb97fb5de4d63fbc5979595/href</a></iframe><p>But having this in the views.py file is still a problem because it’s in a place shared by all of your team and you have to keep track of removing it everytime you commit the code.</p><p>The ideal solution would be to completely remove references in files that are actively changed by your team and make it easier for you to use, change or disable these patches.</p><p>We can achieve this by moving the monkey-patch block to your local settings file (if you are not familiar, <a href="https://stackoverflow.com/questions/4909958/django-local-settings/4909964#4909964">here’s a reference</a> on this configuration) but then<em>, </em>due to how Django load your project’s files, it is necessary to wrap your code in a function and call it in your project’sAppConfig:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d682b481b74186af4be1ff0335103816/href">https://medium.com/media/d682b481b74186af4be1ff0335103816/href</a></iframe><p>And with that, whenever your view is loaded, your form will be filled and you don’t need to worry about it interfering with your VCS anymore (since your local configuration file should be already ignored).</p><p>But <em>please</em> be a good developer and test (and even unit-test!) your code thoroughly with your monkey-patches disabled and with different inputs so you won’t end up with unexpected problems in production when people start using your website for real.</p><p>We can even improve and add a simple structure to enable and disable the monkey-patching so it’s even easier to use them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/032e329b1fa696d27046185bf5b8f571/href">https://medium.com/media/032e329b1fa696d27046185bf5b8f571/href</a></iframe><p>So instead of erasing or commenting your blocks, just use the flags to turn them on or off as needed and reload your server to see the changes.</p><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/icarovirtual/lemoncode/tree/master/monkey-patch">icarovirtual/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1de778d61d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/monkey-patch-f1de778d61d3">A simple and clean way to monkey-patch your apps — Django</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaner views and less repetition with extra objects from your URLs  —  Django]]></title>
            <link>https://medium.com/lemon-code/extra-objects-mixin-9597e2b6b0f8?source=rss----ffec8e390ec3---4</link>
            <guid isPermaLink="false">https://medium.com/p/9597e2b6b0f8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ícaro]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 19:20:15 GMT</pubDate>
            <atom:updated>2020-04-23T01:39:54.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extra objects from your URLs with cleaner views and less repetition — Django</h3><h4>For those moments when a single object is not enough</h4><figure><img alt="Photo by Irina on Unsplash, snippet by @carbonapp" src="https://cdn-images-1.medium.com/max/1024/1*GCW4hTkdvyi7bu7hAKAxIQ.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/3a6bRScDqLI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Irina</a> on <a href="https://unsplash.com/search/photos/lime?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>, snippet from <a href="https://carbon.now.sh/yFl2AxvkYfmJ6r2Srqrc">@carbonapp</a></figcaption></figure><p>When working with Django <a href="https://ccbv.co.uk/">class-based views</a> it’s often common to simply use the view’s object to populate forms, perform validations and other actions depending on your business logic.</p><p>What if you need to do that in an instance that is not the current view’s object? You <em>could</em> get it from a relation or load it manually which is trivial, but things can get messier depending on what your view needs to do like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dfc2a800848c9779bcdd26713c7c09a/href">https://medium.com/media/4dfc2a800848c9779bcdd26713c7c09a/href</a></iframe><p>Doing this can lead to <em>not so great</em> code because it’s not DRY, it’s hard to refactor, can be confusing and have other problems that you’ll only find out six months later when you need to come back to maintain and change it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FePsV4lBfsrPmo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FePsV4lBfsrPmo&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FePsV4lBfsrPmo%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e03f37bbb26691484692c8455491d22/href">https://medium.com/media/6e03f37bbb26691484692c8455491d22/href</a></iframe><p>Django is amazingly built so we can take inspiration from what it already provides us to create or own classes, functions and more. With that in mind, the <a href="https://ccbv.co.uk/projects/Django/2.0/django.views.generic.detail/SingleObjectMixin/">SingleObjectMixin</a> does exactly what we needed above as it’s used to “Provide the ability to retrieve a single object for further manipulation.”</p><p>So we can create a new <a href="https://en.wikipedia.org/wiki/Mixin">mixin</a> with a behavior simpler but similar to it which can be used along without conflict in how they are executed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f9bdc011ef8a534334b4adca85e490/href">https://medium.com/media/87f9bdc011ef8a534334b4adca85e490/href</a></iframe><p>Define an extra model and it’s instance will be loaded based on the view’s URL arguments (the PK or a slug can be used). It’s simple, gets one job done and is reusable and certainly helps with the problems we faced before.</p><p>Below we have a sample of it’s usage that includes setting up the mixin and using it in the view and in it’s URL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9a8ad2b355a598496d9f1da087ddf32/href">https://medium.com/media/a9a8ad2b355a598496d9f1da087ddf32/href</a></iframe><p>Instead of using relations and functions to load the instance, we simply setup the mixin with what we needed and used it’s object_extra accessors for that.</p><p>If you are feeling adventurous, you could even expand the mixin to load two or more extra objects by adding more model fields and URL arguments.</p><p>All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.</p><p><a href="https://github.com/ihhcarus/lemoncode/tree/master/extraobjectmixin">ihhcarus/lemoncode</a></p><p>🍋 🍋 🍋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9597e2b6b0f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lemon-code/extra-objects-mixin-9597e2b6b0f8">Cleaner views and less repetition with extra objects from your URLs  —  Django</a> was originally published in <a href="https://medium.com/lemon-code">Lemon Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>