<?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[Django Musings - Medium]]></title>
        <description><![CDATA[My personal notes and thoughts on Django Web Development - Medium]]></description>
        <link>https://medium.com/django-musings?source=rss----b61cdf9ae3d6---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Django Musings - Medium</title>
            <link>https://medium.com/django-musings?source=rss----b61cdf9ae3d6---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:15:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/django-musings" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Customizing the Django Admin site]]></title>
            <link>https://medium.com/django-musings/customizing-the-django-admin-site-b82c7d325510?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/b82c7d325510</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Wed, 11 May 2016 20:47:32 GMT</pubDate>
            <atom:updated>2016-05-12T15:25:04.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Django’s official doc <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/">here</a></p><p>Let’s start by saying that Django’s admin site is spectacular. It can literally save you months of work, but having said that, one thing that one needs to understand is that Django’s admin site is only ok as an internal tool. It is not, and never has been intended to be, an end user tool. Or in the words of Django’s doc:</p><blockquote>The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.</blockquote><p>The reason for that is that the admin site works by doing introspection on your Model classes so it will expose all your data and DB schema and while it provides ways to customize it at your heart’s content, if you need to customize it you will probably be better replacing it.</p><p>What I am going to explain next are ways to tailor it a little to make it more powerful but not with the intention of changing the way it works.</p><h4>The AdminSite object</h4><p>If you’ve been using the admin app you probably already created an <strong>admin.py</strong> file in your Django app and add it a bunch of calls like this one (if not you’ll need to check the <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial02/">admin tutorial</a>):</p><pre># admin.py<br>from django.contrib import admin</pre><pre>admin.site.register(Book)<br>admin.site.register(Author)</pre><p>The <strong>admin.py</strong> file is automatically looked for and imported by the Admin Django application when it launches so this is the place where you hook your models into the admin app.</p><p>Those <strong>admin.site.register()</strong> calls do exactly that.</p><p>But that <strong>admin.site</strong> object is the main object that represents your Admin and it provides customization options (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#adminsite-objects">documentation</a>).</p><p>These are the ones that I always change:</p><p><strong>admin.site.site_header</strong>, this is the “Django Administration” &lt;h1&gt; text that you find when you enter the site.</p><p><strong>admin.site.site_title</strong>, same thing, but as &lt;title&gt;</p><p><strong>admin.site.index_title, </strong>this is the heading that appears with a default text of “Site administration”(set it to blank if you don’t want to use it)</p><p>If you want to change that view you can set your own template modifying <strong>admin.site.index_template</strong> and <strong>admin.site.app_template</strong>.</p><p>If you want to just change the CSS what you can do is to specify here your own template and that template to extend the default one. Of course in your new template you would be adding your own CSS file.</p><p>(Same thing with the other template options)</p><h4>Customizing the list views</h4><p>The one thing that I care most to customize is the list view (or Change view rather how the documentation calls it). This is the view that it is used when you select a Model and you get a list with all that Model instances in your DB.</p><p>And to do that what you need to do next is to create a <strong>ModelAdmin</strong> instance. Like this:</p><pre># admin.py<br>from django.contrib import admin<br>import models</pre><pre>@admin.register(models.Author)<br>class AuthorAdmin(admin.ModelAdmin):<br>  date_hierarchy = &#39;created&#39;<br>  search_fields = [&#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;]<br>  list_display = (&#39;first_name&#39;,&#39;last_name&#39;,&#39;email&#39;)<br>  list_filter = (&#39;status&#39;,)</pre><p>Let’s dissect that example.</p><p>the <strong>@admin.register()</strong> decorator does the same thing as</p><pre>admin.site.register(models.Author, AuthorAdmin)</pre><p>It just shorter, what we are doing is registering the <strong>Author</strong> model in the admin app but also telling the app that it needs to use <strong>AuthorAdmin</strong> as <strong>ModelAdmin</strong>.</p><p>The <strong>ModelAdmin</strong> is how you customize its appearance.</p><p>The <strong>date_hierarchy </strong>(<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.date_hierarchy">here</a>) when set will make the app show a “timeline browser”. So you can use it to filter by date (ie, all model instances from July of 2015). The value need to be a Date or Datetime field from your model.</p><p>The <strong>search_fields</strong> (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">here</a>), is a list of “QuerySet” fields, that can be used to filter search your result set. Here you can use as value any join expression, for instance “coauthor__name”</p><p>The <strong>list_display</strong> (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display">here</a>) is a tuple of field names. If set instead of being the view a single list, that list can be turned into a table! And in that case <strong>list_display</strong> the fields to be columns of such table.</p><p>Now. I said that it is a tuple of field names, but it can contain <strong>Model </strong>fields as well <strong>ModelAdmin </strong>fields. So you can extend what is shown here by adding a method in your <strong>ModelAdmin </strong>that returns complex query (this is useful because you can’t use <strong>QuerySet </strong>joins operations here, like “<strong>coauthor__first_name</strong>” kind of thing. Check the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display">doc </a>for more info)</p><p>The <strong>list_filter</strong> (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter">here</a>) is another tuple. If present then at the right of the table a filter box will be added with options to filter the given fields. This is particularly useful for Choice fields. (for free-text fields doesn’t make sense)</p><p>Rounding up. You can customize the Django admin and turn it into a very powerful DB console. It will still be something of an internal tool, but it will be a very powerful internal tool.</p><p>The options mentioned above are my favorite, are plenty more, and you can also customize the look and feel at your hearts content by replacing the defaults templates and by adding custom CSS (I don’t usually do it because it’s an internal tool after all)</p><p>You can find all that in the official doc. <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin">Here</a>.</p><p>PS: this talk seems interesting: <a href="https://opbeat.com/events/djangocon-eu-2016/#going-with-the-flow-with-django-admin">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82c7d325510" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/customizing-the-django-admin-site-b82c7d325510">Customizing the Django Admin site</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding User Login to your django site]]></title>
            <link>https://medium.com/django-musings/adding-user-login-to-your-django-site-e19dd6853e92?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/e19dd6853e92</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Tue, 10 May 2016 19:23:44 GMT</pubDate>
            <atom:updated>2016-05-10T19:23:44.026Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first part of a series on customizing your django site and understanding the authentication middleware of Django.</p><p>In this first example we are going to explain how to add login capabilities to your already existing web app that currently uses django admin.</p><p>So. You have your web app. and some views you want to have them protected. How do you do that? Easy. with this decorators:</p><pre>@login_required()<br>def my_view(request):<br>  ...</pre><p>The <strong>login_required()</strong> decorator will make sure that the view is executed on an active logged in session. If not, it will redirect the user to the login page.</p><p>In addition to <strong>login_required()</strong> you can use:</p><pre>@staff_member_required()<br>def my_view(request):<br>  ...</pre><p>With <strong>staff_member_required()</strong> it will not only check that the user is logged in but also has the “ <strong>is_staff</strong>” flag turned on (this is a checkbox that you can set up in the admin interface)</p><p>What about if you want to use other type of check, then you can use the <strong>user_passes_test()</strong> decorator that accepts a callable and will invoke it to determine if the user can or can’t access the view. Example:</p><pre>def email_check(user):<br>  return user.email.endswith(&quot;something.com&quot;)</pre><pre>@user_passes_test(email_check)<br>def my_view(request):<br>  ...</pre><p>The <strong>user_passes_tests()</strong> help is <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.decorators.user_passes_test">here</a>.</p><p>Using this 3 decorators you can control which view has public access and which view has a more restrictive access.</p><p>But we are not complete. We need to tell django how the user needs to login. All these decorators are fully customizable and you can pass your own login url, but by default it will use: “/accounts/login/”. So if you want you can just add that URL to your URLConf and set it with your own view.</p><p>Or better yet, use the one that is part of Django:</p><pre>from django.contrib.auth import views as auth_views<br>...<br>url(https://medium.com/r&#39;^accounts/login/r&#39;^accounts/login/$&#39;, auth_views.login#39;,%20auth_views.login)</pre><p>Or, change the default so you redirect to the admin’s site login:</p><pre># add this in your settings.py</pre><pre>LOGIN_URL=”/admin/login/”</pre><p>Django provides a lot of views for all the default auth operations, you can bulk include them with this in your URLConf:</p><pre>url(https://medium.com/&#39;r^&#39;,%20include(&#39;django.contrib.auth.urls&#39;)</pre><p>If you do that you’ll be adding the login, logout, password_reset, and a lot more of views. but none of these views have their template set! <strong>is your responsibility to implement those templates</strong>. You can just include in your app the templates with their default names or pass your own, but for that you can’t use the include() call from above, but you need to add the route explicitly:</p><pre>urlpatterns = [<br> url(https://medium.com/%3Cbr%3E%20%20%20%E2%80%98%5Echange-password/%E2%80%99,%3Cbr%3E%20%20%20auth_views.password_change,%3Cbr%3E%20%20%7B%E2%80%98template_name%E2%80%99:%20%E2%80%98change-password.html%E2%80%99%7D%3Cbr%3E)<br>]</pre><p>OK. That’s it. Here are defined all the auth views and their parameters. <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#all-authentication-views">here</a></p><p>BTW as for providing your own login template you can use as base the one <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#all-authentication-views">here</a></p><p>Note that each template is passed some template arguments, one of those arguments is a form instance with everything that you need to build the form.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19dd6853e92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/adding-user-login-to-your-django-site-e19dd6853e92">Adding User Login to your django site</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do a basic CRUD REST API with an ORM-Less Django]]></title>
            <link>https://medium.com/django-musings/how-to-do-a-basic-crud-rest-api-with-an-orm-less-django-de0a5f491ea2?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/de0a5f491ea2</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Tue, 03 May 2016 14:17:09 GMT</pubDate>
            <atom:updated>2016-05-04T15:39:55.947Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day had a client that needed to build a very basic web service and the only requirement that I had was that this would needed to be done on top of an existing database and table.</p><p>Normally, like when you are doing things from scratch, you would let Django deal with the database and the SQL. You would specify your table as a Model subclass and use the fantastic ORM that Django provides.</p><p>In this occasion though we couldn’t use the ORM, the table was already specified, had live data, and if we attempted to map the current table to a Model defined ad-hoc I wasn’t sure if the fields would match or if it would be a convenient long-term solution.</p><p>Therefore I needed to skip Django’s ORM. BTW, I also questioned if Django was the right platform, I thought on maybe attempting to use Flask, but Django has been constructed from the get go to be highly compartmentalized and for you to use all the parts that you need and to ignore or turn off the parts that you don’t need. So I tried Django.</p><p>Here is how to do it:</p><h4>Project Setup and Settings</h4><p>you start by creating the project as any other project. In the settings you also define your DATABASE as you would if you would use Django’s ORM.</p><p>That is because we DO want to use Django’s DB interface, what we DO NOT want to use is just the Model to SQL translation that it does (the ORM part)</p><p>Start by installing Django, installing your DB python drivers (<strong>psycopg2</strong> for instance if you are using Postgresql), and creating your Django project.</p><p>Then in settings you still add:</p><pre><em># Database<br># https://docs.djangoproject.com/en/1.9/ref/settings/#databases<br><br></em>DATABASES = {<br>    <strong>&#39;default&#39;</strong>: {<br>        <strong>&#39;ENGINE&#39;</strong>: <strong>&#39;django.db.backends.postgresql_psycopg2&#39;</strong>,<br>        <strong>&#39;NAME&#39;</strong>: <strong>&#39;&lt;db name&gt;&#39;</strong>,<br>        <strong>&#39;USER&#39;</strong>: <strong>&#39;&lt;db user&gt;&#39;</strong>,<br>        <strong>&#39;PASSWORD&#39;</strong>: <strong>&#39;&lt;db password&gt;&#39;</strong>,<br>        <strong>&#39;HOST&#39;</strong>: <strong>&#39;localhost&#39;</strong>,<br>        <strong>&#39;PORT&#39;</strong>: <strong>&#39;&#39;</strong>,<br>    }<br>}</pre><p>(BTW my DB was a postgresql)</p><h4>The Models</h4><p>What does change is your <strong>models.py</strong> file.</p><p>I chose to follow some of Django’s architecture choices and mimic their Model and Manager separation. So I ended up implementing a Model class and a Manager class, only that I did without subclassing from Django’s own <strong>models.Model</strong> and <strong>managers.Manager</strong> classes.</p><p>My model class:</p><pre><strong>from </strong>.managers <strong>import </strong>CompanyManager<br><br><strong>class </strong>Company:<br>    objects = CompanyManager()<br>    <strong>def </strong>__init__(self):</pre><pre>        <em># the private key<br>        </em>self.id = None<br><br>        <em># title or name (for displaying purposes) <br>        # of this company (required)<br>        </em>self.name = None<br><br>        <em># email where all emails generated to this company<br>        # will be redirected (required)<br>        </em>self.email = None<br><br>        <em># email of the contact person, in case is different<br>        # from leads_email (optional)<br>        </em>self.contact_email = None<br><br>        <em># phone of the contact person where calls to this company<br>        # should be directed (optional)<br>        </em>self.contact_phone = None<br><br>        <em># contact person first name (optional)<br>        </em>self.contact_first_name = None<br><br>        <em># contact person last name (optional)<br>        </em>self.contact_last_name = None<br><br>        # ... and many more fields ...</pre><pre>    <strong>def </strong>save(self):<br>        <strong>if </strong>self.id <strong>is not </strong>None:<br>            self.objects.update(self)<br>        <strong>else</strong>:<br>            self.objects.insert(self)<br><br>    <strong>def </strong>delete(self):<br>        self.objects.delete(self)</pre><p>The first thing that you need to notice is that the <strong>Company</strong> class has no super class. I am <strong>not</strong> subclassing <strong>models.Model</strong></p><p>Second thing is that none of the fields are “Model Fields” (everything is initialized as None)</p><p>The actions that my Company class supports are 2, <strong>save()</strong> and <strong>delete()</strong>. Save will take care of creating a new instance if this is a new one, or updating an existing one, if not. And those are also delegated to the <strong>objects</strong> object which is an instance of <strong>CompanyManager</strong>.</p><p>My <strong>CompanyManager</strong> is the class that take care of all the SQL. This is again mimicking Django’s architecture.</p><pre><strong>from </strong>django.db <strong>import </strong>connection<br><br><strong>class </strong>CompanyManager():<br>    <strong>def </strong>__init__(self):<br>        <strong>pass<br><br>    </strong>@staticmethod<br>    <strong>def </strong>format_boolean(value):<br>        <strong>return &#39;TRUE&#39; if </strong>value <strong>else &#39;FALSE&#39;<br><br>    </strong>@staticmethod<br>    <strong>def </strong>format_date(value):<br>        <strong>return </strong>value.isoformat()<br><br>    @staticmethod<br>    <strong>def </strong>format_datetime(value):<br>        <strong>return </strong>value.isoformat()<br><br>    @staticmethod<br>    <strong>def </strong>delete(c):<br>        <strong>pass<br><br>    </strong>@staticmethod<br>    <strong>def </strong>update(c):<br>        cursor = connection.cursor()<br>        query = <strong>&quot;&quot;&quot;UPDATE ayudacontador_company<br>                   SET name=&#39;{0}&#39;,<br>                       email=&#39;{1}&#39;,<br>                       contact_email=&#39;{2}&#39;,<br>                       contact_phone=&#39;{3}&#39;,<br>                       contact_first_name=&#39;{4}&#39;,<br>                       contact_last_name=&#39;{5}&#39;,<br>                       web=&#39;{6}&#39;,<br>                       description=&#39;{7}&#39;,<br>                       logo=&#39;{8}&#39;,<br>                       invoicing_data=&#39;{9}&#39;,<br>                       lead_quota=&#39;{10}&#39;,<br>                       notes=&#39;{11}&#39;,<br>                       subscription_active=&#39;{12}&#39;,<br>                       lead_active=&#39;{13}&#39;,<br>                       last_notification_date=&#39;{14}&#39;,<br>                       received_leads_count={15},<br>                       trial_start_date=&#39;{16}&#39;,<br>                       remove_from_guide=&#39;{17}&#39;,<br>                       mailing_active=&#39;{18}&#39;,<br>                       created=&#39;{19}&#39;<br>                   WHERE id={20};&quot;&quot;&quot;</strong>.format(<br>            c.name,<br>            c.email,<br>            c.contact_email,<br>            c.contact_phone,<br>            c.contact_first_name,<br>            c.contact_last_name,<br>            c.web,<br>            c.description,<br>            c.logo,<br>            c.invoicing_data,<br>            c.lead_quota,<br>            c.notes,<br>            CompanyManager.format_boolean(c.subscription_active),<br>            CompanyManager.format_boolean(c.lead_active),<br>            CompanyManager.format_datetime(<br>                                        c.last_notification_date),<br>            c.received_leads_count,<br>            CompanyManager.format_date(c.trial_start_date),<br>            CompanyManager.format_boolean(c.remove_from_guide),<br>            CompanyManager.format_boolean(c.mailing_active),<br>            CompanyManager.format_datetime(c.created),<br>            c.id)<br><br>        cursor.execute(query)<br><br>    @staticmethod<br>    <strong>def </strong>insert(c):<br>        cursor = connection.cursor()<br>        query = <strong>&quot;&quot;&quot;INSERT INTO ayudacontador_company<br>                   (name,email,contact_email,contact_phone,<br>                    contact_first_name,contact_last_name, <br>                    web,description,logo,invoicing_data,<br>                    lead_quota,notes,subscription_active,<br>                    lead_active,last_notification_date,<br>                    received_leads_count,trial_start_date,<br>                    remove_from_guide,mailing_active,<br>                    created)<br>                   VALUES (&#39;{0}&#39;,&#39;{1}&#39;,&#39;{2}&#39;,&#39;{3}&#39;,&#39;{4}&#39;,<br>                           &#39;{5}&#39;,&#39;{6}&#39;,&#39;{7}&#39;,&#39;{8}&#39;,&#39;{9}&#39;,&#39;{10}&#39;,<br>                           &#39;{11}&#39;,&#39;{12}&#39;,&#39;{13}&#39;,&#39;{14}&#39;{15},<br>                           &#39;{16}&#39;,&#39;{17}&#39;,&#39;{18}&#39;,&#39;{19}&#39;);&quot;&quot;&quot;</strong>.format(<br>            c.name,<br>            c.email,<br>            c.contact_email,<br>            c.contact_phone,<br>            c.contact_first_name,<br>            c.contact_last_name,<br>            c.web,<br>            c.description,<br>            c.logo,<br>            c.invoicing_data,<br>            c.lead_quota,<br>            c.notes,<br>            CompanyManager.format_boolean(c.subscription_active),<br>            CompanyManager.format_boolean(c.lead_active),<br>            CompanyManager.format_datetime(<br>                                        c.last_notification_date),<br>            c.received_leads_count,<br>            CompanyManager.format_date(c.trial_start_date),<br>            CompanyManager.format_boolean(c.remove_from_guide),<br>            CompanyManager.format_boolean(c.mailing_active),<br>            CompanyManager.format_datetime(c.created))<br><br>        cursor.execute(query)<br><br>    @staticmethod<br>    <strong>def </strong>all():<br>        cursor = connection.cursor()<br>        query = <strong>&quot;&quot;&quot;SELECT name,email,contact_email,contact_phone,<br>                  contact_first_name,contact_last_name,<br>                  web,description,logo,invoicing_data,lead_quota,<br>                  notes,subscription_active,lead_active,<br>                  last_notification_date,received_leads_count,<br>                  trial_start_date,remove_from_guide,mailing_active,<br>                  created,id<br>                  FROM ayudacontador_company;&quot;&quot;&quot;<br><br>        </strong>cursor.execute(query)<br>        objects = []<br><br>        <strong>from </strong>.models <strong>import </strong>Company<br><br>        <strong>for </strong>row <strong>in </strong>cursor.fetchall():<br>            c = Company()<br>            c.name = row[0]<br>            c.email = row[1]<br>            c.contact_email = row[2]<br>            c.contact_phone = row[3]<br>            c.contact_first_name = row[4]<br>            c.contact_last_name = row[5]<br>            c.web = row[6]<br>            c.description = row[7]<br>            c.logo = row[8]<br>            c.invoicing_data = row[9]<br>            c.lead_quota = row[10]<br>            c.notes = row[11]<br>            c.subscription_active = row[12]<br>            c.lead_active = row[13]<br>            c.last_notification_date = row[14]<br>            c.received_leads_count = row[15]<br>            c.trial_start_date = row[16]<br>            c.remove_from_guide = row[17]<br>            c.mailing_active = row[18]<br>            c.created = row[19]<br>            c.id = row[20]<br>            objects.append(c)<br><br>        <strong>return </strong>objects<br><br>    @staticmethod<br>    <strong>def </strong>get(id):<br>        cursor = connection.cursor()<br>        query = <strong>&quot;&quot;&quot;SELECT name,email,contact_email,contact_phone,<br>                   contact_first_name,contact_last_name,<br>                   web,description,logo,invoicing_data,<br>                   lead_quota,notes,subscription_active,lead_active,<br>                   last_notification_date,received_leads_count,<br>                   trial_start_date,remove_from_guide,<br>                   mailing_active,<br>                   created,id<br>                   FROM ayudacontador_company<br>                   WHERE id={0};&quot;&quot;&quot;</strong>.format(id)<br><br>        cursor.execute(query)<br>        objects = []<br><br>        <strong>from </strong>.models <strong>import </strong>Company<br><br>        <strong>for </strong>row <strong>in </strong>cursor.fetchall():<br>            c = Company()<br>            c.name = row[0]<br>            c.email = row[1]<br>            c.contact_email = row[2]<br>            c.contact_phone = row[3]<br>            c.contact_first_name = row[4]<br>            c.contact_last_name = row[5]<br>            c.web = row[6]<br>            c.description = row[7]<br>            c.logo = row[8]<br>            c.invoicing_data = row[9]<br>            c.lead_quota = row[10]<br>            c.notes = row[11]<br>            c.subscription_active = row[12]<br>            c.lead_active = row[13]<br>            c.last_notification_date = row[14]<br>            c.received_leads_count = row[15]<br>            c.trial_start_date = row[16]<br>            c.remove_from_guide = row[17]<br>            c.mailing_active = row[18]<br>            c.created = row[19]<br>            c.id = row[20]<br>            objects.append(c)<br><br>        <strong>return </strong>None <strong>if </strong>len(objects) == 0 <strong>else </strong>objects[0]</pre><p>As you see we are executing SQL statements directly. But we are using Django’s DB Connection feature and letting Django deal with creating a pool of connections and all that stuff.</p><p>BTW doc for performing raw SQL queries on Django you can find it <a href="https://docs.djangoproject.com/en/1.9/topics/db/sql/">here</a>.</p><p>So as you see our manager provides the CRUD methods and is responsible for interfacing between our “ Model” instance, Company, and the Database SQL data types.</p><p>As we are responsible for writing the queries we are responsible for formating our python fields, such as Booleans and Datetimes, into their SQL compatible alter-egos. And here <strong>you need to take into consideration what your DB engine supports and expects.</strong> It’s not the same MySQL than PostgreSQL. Beware of that.</p><p>But reading the SQL and getting Python types back we don’t have to worry. Django’s connection takes care of that apparently.</p><h4>The REST Framework</h4><p>Ok. Up to this point we have a fully functional Model and Manager. Now we want to create our REST API and for that we are using rest_framework, so execute:</p><pre>pip install djangorestframework</pre><p>Now what we need to do is to create our serializers. The serializers are the ones that will interface between our DB and the API output (json or whatever we use)</p><p>create a <strong>serializers.py</strong> and type the following:</p><pre><strong>from </strong>rest_framework <strong>import </strong>serializers<br><br><strong>from </strong>.models <strong>import </strong>Company<br><br><br><strong>class </strong>CompanySerializer(serializers.Serializer):<br>    id = serializers.IntegerField(read_only=True)<br>    name = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    email = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    contact_email = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    contact_phone = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    contact_first_name = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    contact_last_name = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    web = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    description = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    logo = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    invoicing_data = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    lead_quota = serializers.IntegerField()<br>    notes = serializers.CharField(required=False, allow_blank=True, max_length=128)<br>    subscription_active = serializers.BooleanField()<br>    lead_active = serializers.BooleanField()<br>    last_notification_date = serializers.DateTimeField(required=False)<br>    received_leads_count = serializers.IntegerField()<br>    trial_start_date = serializers.DateField()<br>    remove_from_guide = serializers.BooleanField()<br>    mailing_active = serializers.BooleanField()<br>    created = serializers.DateTimeField()<br><br>    <strong>def </strong>create(self, validated_data):<br>        c = Company()<br>        c.name = validated_data.get(<strong>&quot;name&quot;</strong>)<br>        c.email = validated_data.get(<strong>&quot;email&quot;</strong>)<br>        c.contact_email = validated_data.get(<strong>&quot;contact_email&quot;</strong>)<br>        c.contact_phone = validated_data.get(<strong>&quot;contact_phone&quot;</strong>)<br>        c.contact_first_name = validated_data.get(<strong>&quot;contact_first_name&quot;</strong>)<br>        c.contact_last_name = validated_data.get(<strong>&quot;contact_last_name&quot;</strong>)<br>        c.web = validated_data.get(<strong>&quot;web&quot;</strong>)<br>        c.description = validated_data.get(<strong>&quot;descrition&quot;</strong>)<br>        c.logo = validated_data.get(<strong>&quot;logo&quot;</strong>)<br>        c.invoicing_data = validated_data.get(<strong>&quot;invoicing_data&quot;</strong>)<br>        c.lead_quota = validated_data.get(<strong>&quot;lead_quota&quot;</strong>)<br>        c.notes = validated_data.get(<strong>&quot;notes&quot;</strong>)<br>        c.subscription_active = validated_data.get(<strong>&quot;subscription_active&quot;</strong>)<br>        c.lead_active = validated_data.get(<strong>&quot;lead_active&quot;</strong>)<br>        c.last_notification_date = validated_data.get(<strong>&quot;last_notification_date&quot;</strong>)<br>        c.received_leads_count = validated_data.get(<strong>&quot;received_leads_count&quot;</strong>)<br>        c.trial_start_date = validated_data.get(<strong>&quot;trial_start_date&quot;</strong>)<br>        c.remove_from_guide = validated_data.get(<strong>&quot;remove_from_guide&quot;</strong>)<br>        c.mailing_active = validated_data.get(<strong>&quot;mailing_active&quot;</strong>)<br>        c.created = validated_data.get(<strong>&quot;created&quot;</strong>)<br>        c.save()<br>        <strong>return </strong>c<br><br>    <strong>def </strong>update(self, c, validated_data):<br>        c.id = validated_data.get(<strong>&quot;id&quot;</strong>, c.id)<br>        c.name = validated_data.get(<strong>&quot;name&quot;</strong>, c.name)<br>        c.email = validated_data.get(<strong>&quot;email&quot;</strong>, c.email)<br>        c.contact_email = validated_data.get(<strong>&quot;contact_email&quot;</strong>, c.contact_email)<br>        c.contact_phone = validated_data.get(<strong>&quot;contact_phone&quot;</strong>, c.contact_phone)<br>        c.contact_first_name = validated_data.get(<strong>&quot;contact_first_name&quot;</strong>, c.contact_first_name)<br>        c.contact_last_name = validated_data.get(<strong>&quot;contact_last_name&quot;</strong>, c.contact_last_name)<br>        c.web = validated_data.get(<strong>&quot;web&quot;</strong>, c.web)<br>        c.description = validated_data.get(<strong>&quot;description&quot;</strong>, c.description)<br>        c.logo = validated_data.get(<strong>&quot;logo&quot;</strong>, c.logo)<br>        c.invoicing_data = validated_data.get(<strong>&quot;invoicing_data&quot;</strong>, c.invoicing_data)<br>        c.lead_quota = validated_data.get(<strong>&quot;lead_quota&quot;</strong>, c.lead_quota)<br>        c.notes = validated_data.get(<strong>&quot;notes&quot;</strong>, c.notes)<br>        c.subscription_active = validated_data.get(<strong>&quot;subscription_active&quot;</strong>, c.subscription_active)<br>        c.lead_active = validated_data.get(<strong>&quot;lead_active&quot;</strong>, c.lead_active)<br>        c.last_notification_date = validated_data.get(<strong>&quot;last_notification_date&quot;</strong>, c.last_notification_date)<br>        c.received_leads_count = validated_data.get(<strong>&quot;received_leads_count&quot;</strong>, c.received_leads_count)<br>        c.trial_start_date = validated_data.get(<strong>&quot;trial_start_date&quot;</strong>, c.trial_start_date)<br>        c.remove_from_guide = validated_data.get(<strong>&quot;remove_from_guide&quot;</strong>, c.remove_from_guide)<br>        c.mailing_active = validated_data.get(<strong>&quot;mailing_active&quot;</strong>, c.mailing_active)<br>        c.created = validated_data.get(<strong>&quot;created&quot;</strong>, c.created)<br>        c.save()<br>        <strong>return </strong>c</pre><p>As you see we are <strong>not </strong>using a ModelSerializer, the ModelSerializers from rest_framework are glorious because they read all the data from the Model subclass and automatically generate that code that you see above.</p><p>But here we do it ourselves.</p><p>The serializers here specifies (not unlike Django’s forms or Model classes) the fields that our API inputs/responses will include and their types.</p><p>And with those 2 methods, <strong>create()</strong> and <strong>update()</strong> how to create or modify our Company instances with the data that we took from the API invocations.</p><p>Now we need to create the API endpoints. The views:</p><p>in <strong>views.py</strong> add this:</p><pre><strong>from </strong>django.http <strong>import </strong>HttpResponse<br><strong>from </strong>rest_framework <strong>import </strong>status<br><strong>from </strong>rest_framework.decorators <strong>import </strong>api_view<br><strong>from </strong>rest_framework.response <strong>import </strong>Response<br><strong>from </strong>.models <strong>import </strong>Company<br><strong>from </strong>.serializers <strong>import </strong>CompanySerializer<br><br><br>@api_view([<strong>&#39;GET&#39;</strong>, <strong>&#39;POST&#39;</strong>])<br><strong>def </strong>company_list(request, format=None):<br>    <em>&quot;&quot;&quot;<br>    List all code snippets, or create a new snippet.<br>    &quot;&quot;&quot;<br>    </em><strong>if </strong>request.method == <strong>&#39;GET&#39;</strong>:<br>        companies = Company.objects.all()<br>        serializer = CompanySerializer(companies, many=True)<br>        <strong>return </strong>Response(serializer.data)<br><br>    <strong>elif </strong>request.method == <strong>&#39;POST&#39;</strong>:<br>        serializer = CompanySerializer(data=request.data)<br>        <strong>if </strong>serializer.is_valid():<br>            serializer.save()<br>            <strong>return </strong>Response(serializer.data, status=status.HTTP_201_CREATED)<br><br>        <strong>return </strong>Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>@api_view([<strong>&#39;GET&#39;</strong>, <strong>&#39;PUT&#39;</strong>, <strong>&#39;DELETE&#39;</strong>])<br><strong>def </strong>company_detail(request, id, format=None):<br>    <em>&quot;&quot;&quot;<br>    Retrieve, update or delete a code snippet.<br>    &quot;&quot;&quot;<br>    </em>company = Company.objects.get(id)<br>    <strong>if </strong>company <strong>is </strong>None:<br>       <strong>return </strong>Response(status=status.HTTP_404_NOT_FOUND)<br><br>    <strong>if </strong>request.method == <strong>&#39;GET&#39;</strong>:<br>        serializer = CompanySerializer(company)<br>        <strong>return </strong>Response(serializer.data)<br><br>    <strong>elif </strong>request.method == <strong>&#39;PUT&#39;</strong>:<br>        serializer = CompanySerializer(company, data=request.data)<br>        <strong>if </strong>serializer.is_valid():<br>            serializer.save()<br>            <strong>return </strong>Response(serializer.data)<br>        <strong>return </strong>Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br>    <strong>elif </strong>request.method == <strong>&#39;DELETE&#39;</strong>:<br>        company.delete()<br>        <strong>return </strong>HttpResponse(status=status.HTTP_204_NO_CONTENT)</pre><p>Same as before. If we used one of rest_framework’s shorthands for views creation it would do all of that in 2 lines but as we are not using Django’s ORM we have to do this ourselves.</p><p>Last but not least we need to now modify our <strong>urls.py</strong> so these views can be reached:</p><pre><strong>from </strong>django.conf.urls <strong>import </strong>url<br><strong>from </strong>rest_framework.urlpatterns <strong>import </strong>format_suffix_patterns<br><br><strong>from </strong>table_orders <strong>import </strong>views<br><br>urlpatterns = [<br>    url(https://medium.com/%3Cstrong%3Er&#39;^companies/<strong>r&#39;^companies/$&#39;</strong>, views.company_list#39;%3C/strong%3E,%20views.company_list),<br>    url(https://medium.com/%3Cstrong%3Er&#39;^companies/(?P&lt;id&gt;[0-9]+)/$&#39;</strong>, views.company_detail),<br>]<br><br>urlpatterns = format_suffix_patterns(urlpatterns)</pre><p>And in the root <strong>urls.py</strong>:</p><pre><strong>from </strong>django.conf.urls <strong>import </strong>url, include<br><strong>from </strong>django.contrib <strong>import </strong>admin<br><br><strong>from </strong>table_orders <strong>import </strong>views<br><br>urlpatterns = [<br>    url(https://medium.com/%3Cstrong%3Er&#39;^&#39;%3C/strong%3E,%20include(%3Cstrong%3E&#39;table_orders.urls&#39;%3C/strong%3E)),<br>    url(https://medium.com/%3Cstrong%3Er&#39;^admin/&#39;%3C/strong%3E,%20admin.site.urls),<br>]</pre><p>And that’s it !</p><p>Now you can just run the server and visit <a href="http://127.0.0.1:8000/companies">http://127.0.0.1:8000/companies</a> and start playing with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0a5f491ea2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/how-to-do-a-basic-crud-rest-api-with-an-orm-less-django-de0a5f491ea2">How to do a basic CRUD REST API with an ORM-Less Django</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[django-cms: this is not a review]]></title>
            <link>https://medium.com/django-musings/django-cms-this-is-not-a-review-464fa086e39d?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/464fa086e39d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Wed, 27 Apr 2016 20:00:50 GMT</pubDate>
            <atom:updated>2016-04-27T20:00:49.878Z</atom:updated>
            <content:encoded><![CDATA[<p>I am trying different blog and CMS solutions that are Django native. The first one that I came into was <strong>django-cms</strong>. The following is NOT a review. I only played with it a little, this is more like a ‘done the tutorial’ and ‘ first impressions’ type of post.</p><h4>What is <strong>django-cms</strong></h4><p>Its an open source project for a CMS implementation on Django.</p><p>It seems pretty complete, used by many, and also they have a (I assume) a paid service for a cloud hosted version. Which is good, because that means that it is actively worked on.</p><h4>So, first impressions…</h4><p>From the get go, looking at their homepage, all the logos and sites that use <strong>django-cms</strong>, the project seemed like the PRO version of all the other blog apps and CMS projects that I found.</p><p>Just check it: <a href="http://www.django-cms.org/en/">http://www.django-cms.org/en/</a></p><p>I immediately went to the docs, and started their tutorial: <a href="http://docs.django-cms.org/en/latest/">http://docs.django-cms.org/en/latest/</a></p><p>So. Documentation-wise and from the look of their site and everything it looks like this project has an active community, and it is currently maintained which is really, but really, a pro (other projects had their latest commits 3 to 4 years ago)</p><h4>The Tutorial</h4><p>The tutorial walks you on how to install and setup <strong>django-cms</strong>, it seems that this is a monster kind of app. You can do everything with it, it is very, very, flexible. And of course that gives you also complexity.</p><p>You can, as expected, customize the look’n feel of every page, it works as any other Django app, so you just do what you already know while editing .html template files.</p><p>Conceptually it is a CMS, so you can make a blog, where the C on CMS are Posts, but you can also do other type of content. A Content type is called Plugin in <strong>django-cms</strong>, and you can add whatever type of content you want.</p><p>You can interactively add/remove pages to the CMS, and modify the pages structure (layout) and its content.</p><p>There are also a lot of plugins and apps already implemented for <strong>django-cms</strong> so for instance you don’t need to implement a Blog, there are already a News blog app for <strong>django-cms</strong> (In the tutorial it shows one)</p><h4>Conclusion</h4><p>My first impressions as I was saying is that this project is a beast. If I needed to do something CMS-like I know that <strong>django-cms</strong> can support it. What I don’t know if it is too much complex for my taste.</p><p>In the documentation they show how to add different types of content, and how to customize its views but something I didn’t find was how to modify the login. Say that instead of having local users I want to use OAuth and login with any OAuth provider (Twitter, FB, … etc)</p><p><strong>ps: </strong>Well… <strong>django-cms</strong> uses theDjango native auth system so in theory it should be possible to use something made for plain Django, not just django-cms. I also found this post: <a href="https://groups.google.com/forum/#!topic/django-cms/Z0TyV8VpbEc">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=464fa086e39d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/django-cms-this-is-not-a-review-464fa086e39d">django-cms: this is not a review</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Multiple Settings Files Pattern]]></title>
            <link>https://medium.com/django-musings/the-multiple-settings-files-pattern-a6e6066d2a69?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/a6e6066d2a69</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Mon, 18 Apr 2016 21:38:47 GMT</pubDate>
            <atom:updated>2016-06-02T20:32:37.184Z</atom:updated>
            <content:encoded><![CDATA[<p>I read this first in <a href="https://www.twoscoopspress.com/products/two-scoops-of-django-1-8">Two Scoops of Django</a> a while back.</p><p>When we start working with Django we learn fast that we’ll need to use some settings values to run the app in development mode, and some other setting values for when we deploy the app in production.</p><p>What can we do to manage multiple setting scenarios in a way that it is neatly organized and keep everything versioned?</p><h4>Meet The Multiple Settings Files pattern</h4><p>After we create our django project we end up with a directory like this:</p><pre>\manage.py<br>\app_name\_init_.py<br>\app_name\settings.py<br>\app_name\admin.py<br>\app_name\urls.py<br>\app_name\wsgi.py<br>...</pre><p>With <strong>settings.py</strong> our settings module and where all django default configuration is.</p><p>Move <strong>settings.py</strong> file into a ‘<strong> settings</strong>’ package and rename to (for example) <strong>base.py</strong>:</p><p>So you should end up with something like this:</p><pre>\manage.py<br>\proj_name\_init_.py<br>\proj_name\settings\_init_.py<br>\proj_name\settings\base.py  # all common settings<br>\proj_name\settings\local.py  # local deployment only settings<br>\proj_name\settings\production.py  # production only settings<br>\proj_name\settings\test.py  # test only settings<br>\proj_name\admin.py<br>\proj_name\urls.py<br>\proj_name\wsgi.py</pre><p>I’ll explain in a second the <strong>local.py</strong>, <strong>production.py</strong> and <strong>test.py</strong> files. But for now understand that they will be our new configuration files and we are going to tell Django which one to use with the <strong>DJANGO_SETTINGS_MODULE </strong>environment variable.</p><p>So while on production you will have to have add this environment variable declaration:</p><pre>set DJANGO_SETTINGS_MODULE=proj_name.settings.production</pre><p>and while on testing:</p><pre>set DJANGO_SETTINGS_MODULE=proj_name.settings.test</pre><p>and you get the idea.</p><p>But what about the new files.</p><p>If you remember you have all your original settings in <strong>base.py</strong> file, what you need to do now is to create empty <strong>production.py</strong>, <strong>local.py</strong> and <strong>test.py</strong> files and import <strong>base.py</strong> in them and override only what you need.</p><p>Example:</p><pre># settings/production.py</pre><pre>from .base import *</pre><pre># Everything from base is here, we overwrite only what we need:</pre><pre>DEBUG=False<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,<br>        &#39;NAME&#39;: get_env_variable(&#39;DB_NAME&#39;),<br>        &#39;USER&#39;: get_env_variable(&#39;DB_USER&#39;),<br>        &#39;PASSWORD&#39;: get_env_variable(&#39;DB_PASS&#39;),<br>        &#39;HOST&#39;: &#39;localhost&#39;,<br>        &#39;PORT&#39;: &#39;&#39;,<br>    }<br>}<br>...</pre><p>Example:</p><pre># settings/local.py</pre><pre>from .base import *</pre><pre># Everything from base is here, we overwrite only what we need:</pre><pre>DEBUG=True<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,<br>        &#39;NAME&#39;: os.path.join(BASE_DIR, &#39;db.sqlite3&#39;),<strong><br></strong>    }<br>}<br>...</pre><p>And voila.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e6066d2a69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/the-multiple-settings-files-pattern-a6e6066d2a69">The Multiple Settings Files Pattern</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What to do with passwords and secrets?]]></title>
            <link>https://medium.com/django-musings/what-to-do-with-passwords-and-secrets-16c2409bfdd8?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/16c2409bfdd8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Mon, 18 Apr 2016 21:11:45 GMT</pubDate>
            <atom:updated>2016-04-18T21:11:44.891Z</atom:updated>
            <content:encoded><![CDATA[<p>What should we do with all the secret stuff that we have in our code?</p><p>Meaning, Django’s SECRET_KEY setting, various user and password credentials (EMAIL, DATABASE, …), API KEYs to 3rd party REST API, so on…</p><p><strong>Option one</strong>. We could just hardcode it in our code. Yes. That’s terrible.</p><p>For starters if you keep it in your code then it goes into your Code Repository. Now you are sharing your secret stuff with everybody else in your project. And if you don’t have team members it doesn’t matter. This secret stuff is now being backed up and stored and became vulnerable to theft or other stuff.</p><p><strong>Option two</strong>. Keep it in the code, but avoid committing it with the rest of the files.</p><p>Depends on how you do it. If you keep a separate .py file with ONLY these settings, and use the multiple setting files pattern (next article) and avoid committing this file with the creds. Then ok. It might work.</p><p>So you only need to remember to avoid ever committing it by mistake.</p><p><strong>option three</strong>. keep them in environment variables. This is my favorite. I took it from <a href="https://www.twoscoopspress.com/products/two-scoops-of-django-1-8">Two Scoops From Django</a>. In the book they do it like these.</p><p>In your settings file you add:</p><pre>import os<br>from django.core.exceptions import ImproperlyConfigured</pre><pre>def get_env_variable(name):<br><em>  “””Gets the environment variable or throws ImproperlyConfigured<br>     exception<br>     :rtype: object<br>  “””</em></pre><pre>  try:<br>    return os.environ[name]</pre><pre>    except KeyError:<br>      raise ImproperlyConfigured(<br>                    ‘Environment variable “%s” not found.’ % name)</pre><p>And now every time you need a parameter that you want out of your code you do this:</p><pre><em># SECURITY WARNING: keep the secret key used in production secret!<br></em>SECRET_KEY = get_env_variable(<strong>&#39;</strong>SECRET_KEY<strong>&#39;</strong>)</pre><p>And that’s it.</p><p>Of course for this to work you have to have a shell file (.sh, .bat, .cmd, whatever) that will initialize your environment with the proper values.</p><p>But that’s not biggie. Every IDE and deployment environment provides you a way to customize your app’s environment variables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c2409bfdd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/what-to-do-with-passwords-and-secrets-16c2409bfdd8">What to do with passwords and secrets?</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[httpie is yummy]]></title>
            <link>https://medium.com/django-musings/httpie-is-yummy-6a3d82b5c0ce?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a3d82b5c0ce</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Sun, 17 Apr 2016 22:35:07 GMT</pubDate>
            <atom:updated>2016-04-17T22:35:07.324Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are developing REST APIs you need a client to test them.</p><p>If you are on Linux you use curl.</p><p>If you are on Windows, you can look for a Chrome or Firefox plugin (I used poster a while ago) but I recommend you to use httpie</p><p>httpie is exactly like curl.</p><p>To install it do:</p><pre>pip install httpie</pre><p>This will add an <strong>http </strong>binary and now to use it you just do it like this:</p><pre>http -a john:psw123 POST <a href="http://127.0.0.1/books/">http://127.0.0.1/books/</a> title=something<br>http GET htp://127.0.0.1:800/books/1/</pre><p>and so on…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a3d82b5c0ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/httpie-is-yummy-6a3d82b5c0ce">httpie is yummy</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting with django-rest-framework]]></title>
            <link>https://medium.com/django-musings/starting-with-django-rest-framework-d6f42105bf1d?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/d6f42105bf1d</guid>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Sun, 17 Apr 2016 22:30:27 GMT</pubDate>
            <atom:updated>2016-04-17T22:30:27.106Z</atom:updated>
            <content:encoded><![CDATA[<p>Django-Rest-Framework doc <a href="http://www.django-rest-framework.org/">here</a>.</p><p>Let’s say that you want to create a REST API and you want to use rest_framework, here is what you need to know to start using it right away (BTW you can also read their official tutorial, <a href="http://www.django-rest-framework.org/tutorial/1-serialization/">here</a>).</p><h4>Configuration</h4><p>All rest_framework configuration goes into a dictionary in your <strong>settings.py</strong> file called REST_FRAMEWORK.</p><p>example:</p><pre>REST_FRAMEWORK = {<br> ‘DEFAULT_PERMISSION_CLASSES’:<br>     [‘rest_framework.permissions.IsAdminUser’],<br> ‘PAGE_SIZE’: 10<br>}</pre><h4>Serializers</h4><p>Serializers are the classes responsible for taking, lets say, Model instances, and serializing them into, let’s say, a JSON representation.</p><p>Serializers work both ways, from Model to JSON and from JSON to Model.</p><p>So your class needs to have a Serializer for each ‘API object’ that you will be representing within your API. Typically you put these serializers in a <strong>serializers.py</strong> module.</p><p>A Serializer looks like this:</p><pre>from rest_framework import serializers<br>from .models import Book</pre><pre>class BookSerializer(serializers.Serializer):<br>  pk = serializers.IntegerField(read_only=True)<br>  title = serializers.CharField(required=False, <br>                                allow_blank=True, max_length=100)<br>  author = serializers.CharField()</pre><pre>  def create(self, validated_data):<br>    “””<br>    Create and return a new `Book` instance, given the <br>    validated data.<br>    “””<br>    return Book.objects.create(**validated_data)</pre><pre>  def update(self, instance, validated_data):<br>    “””<br>    Update and return an existing `Book` instance, <br>    given the validated data.<br>    “””<br>  instance.title = validated_data.get(‘title’, instance.title)<br>  instance.code = validated_data.get(‘code’, instance.code)<br>  instance.save()<br>  return instance</pre><p>It is much alike declaring a Form in Django (or a Model). You specify the fields of your API objects as in a form.</p><p>The methods <strong>create </strong>and <strong>update </strong>let’s you code how the transformation from ‘API object’ to ‘YOUR DOMAIN object’ occurs.</p><p>Now. The one above is the <em>complex</em> way of using serializers, if you are handling Model instances you can just do it this way:</p><pre>class BookSerializer(serializers.HyperlinkedModelSerializer):<br> class Meta:<br>   model = Book<br>   fields = (‘url’, ‘title’, ‘author&#39;)</pre><p>The class <strong>HyperlinkedModelSerializer </strong>(which extends <strong>ModelSerializer</strong>) will automatically read the fields from your model, and now how to create and update their instances.</p><p>In the Meta subclass you specify the actual model that this serializer needs to work with, and the fields that will be included in the representation of the object.</p><p><strong>HyperlinkedModelSerializer </strong>does something more. That field ‘<strong>url</strong>’ is the url that will act as an ID for the object, this is better than just using the plain ‘<strong>pk</strong>’ of the model instances. But if you don’t want that you can just use <strong>ModelSerializer</strong>.</p><h4>Requests and Responses</h4><p>rest_framework provides its own <strong>Request </strong>and <strong>Response </strong>objects to aid you in building your Views (which will be your REST API endpoints)</p><p>The <strong>Request </strong>object will for instance include a <strong>.data</strong> dictionary with the data of the request, no more <strong>.GET</strong>, <strong>.POST</strong> or <strong>.PUT</strong> dictionaries.</p><p>The <strong>Response </strong>object will accept ‘unrendered data’ (your django’s object) and know how to render it in whatever type of presentation if needs to be rendered (as you will see you can select the type of presentation to use)</p><h4>Views</h4><p>Your REST API endpoints are Views in your django’s app. For building this View rest_framework provides many facilities.</p><p>If you want to use a function-based view, you can use the <strong>@api_view</strong> decorator.</p><p>For class-based views you have the <strong>APIView </strong>base class.</p><p>These wrappers will take care of translating Django’s own Request object into rest_framework’s one, as well as taking Response object as return value</p><p>They will also handle some errors by themselves (for instance they will know to answer METHOD_NOT_ALLOWED if you didn’t declare an operation)</p><p>Here an example for <strong>@api_view</strong>:</p><pre>from django.http import HttpResponse<br>from rest_framework import status<br>from rest_framework.decorators import api_view<br>from rest_framework.parsers import JSONParser<br>from rest_framework.response import Response</pre><pre>from snippets.models import Snippet<br>from snippets.serializers import SnippetSerializer</pre><pre><a href="http://twitter.com/api_view">@api_view</a>([‘GET’, ‘POST’])<br>def snippet_list(request):<br>  if request.method == ‘GET’:<br>    snippets = Snippet.objects.all()<br>    serializer = SnippetSerializer(snippets, many=True)<br>    return Response(serializer.data)</pre><pre>  elif request.method == ‘POST’:<br>    data = JSONParser().parse(request)<br>    serializer = SnippetSerializer(data=data)</pre><pre>    if serializer.is_valid():<br>      serializer.save()<br>      return Response(serializer.data, <br>                      status=status.HTTP_201_CREATED)</pre><pre>    return Response(serializer.errors,<br>                    status=status.HTTP_400_BAD_REQUEST)</pre><p>Here is a view that will check the type of operation, read the data from the serializer and do whatever it needs to do. This is all too much work. rest_framework provides you with class-based views that already do all of this automatically so you can write views in 3 lines of codes:</p><pre>from snippets.models import Snippet<br>from snippets.serializers import SnippetSerializer<br>from rest_framework import generics</pre><pre>class SnippetList(generics.ListCreateAPIView):<br> queryset = Snippet.objects.all()<br> serializer_class = SnippetSerializer</pre><pre>class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):<br> queryset = Snippet.objects.all()<br> serializer_class = SnippetSerializer</pre><p>Check generics to see what types of APIView the framework provides.</p><h4>URLConf</h4><p>Now that we have our Views coded we need to add our url mappings in the urls.py of our app. You can do it like this:</p><pre>from django.conf.urls import url<br>from snippets import views</pre><pre>urlpatterns = [<br> url(https://medium.com/r%E2%80%99%5Esnippets/$%E2%80%99,%20views.snippet_list),<br> url(https://medium.com/r%E2%80%99%5Esnippets/(?P&lt;pk&gt;[0%E2%80%939]+)/$’, views.snippet_detail),<br>]</pre><h4>Authentication</h4><p>For implementing this we need is to specify what type of access each View has and that can be done very easily overriding <strong>permission_classes</strong> field:</p><pre>from django.contrib.auth.models import User</pre><pre>from rest_framework import generics<br>from rest_framework import permissions</pre><pre>from snippets.models import Snippet<br>from snippets.serializers import SnippetSerializer, UserSerializer</pre><pre>class SnippetList(generics.ListCreateAPIView):<br> permission_classes = (permissions.IsAuthenticatedOrReadOnly,)<br> queryset = Snippet.objects.all()<br> serializer_class = SnippetSerializer</pre><p>The <strong>permissions.IsAuthenticatedOrReadOnly</strong> permission scheme will gave access read-only for all the SAFE operations (GET, HEAD, OPTIONS, …), and access to the other operations <strong>only</strong> for authenticated users.</p><p>Here rest_framework will work alongside django’s user authentication system.</p><p>There are other types of permission schemes, but if you want to do something custom you just need to add the class in the permission_classes field, and implement the class with something like this:</p><pre>from rest_framework import permissions</pre><pre>class IsOwnerOrReadOnly(permissions.BasePermission):<br> def has_object_permission(self, request, view, obj):<br>   if request.method in permissions.SAFE_METHODS:<br>      return True</pre><pre>   return obj.owner == request.user</pre><p>in this example <strong>obj.owner</strong> would point to a field on our model and is being compared the user specified in the in the Request session.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f42105bf1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/starting-with-django-rest-framework-d6f42105bf1d">Starting with django-rest-framework</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Current DateTime for default value in a Model? Use callables]]></title>
            <link>https://medium.com/django-musings/current-datetime-for-default-value-in-a-model-use-callables-85e092e68fa6?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/85e092e68fa6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Sat, 16 Apr 2016 18:52:25 GMT</pubDate>
            <atom:updated>2016-04-16T18:52:25.516Z</atom:updated>
            <content:encoded><![CDATA[<p>So. Let’s say that you have:</p><pre># app/models.py<br>from django.db import models<br>from datetime import datetime</pre><pre>class Book(models.Model):<br>  name = models.CharField(max_length=128)<br>  release_date = models.DateTimeField(default=datetime.now())</pre><p>With <strong>release_date</strong> getting the current date and time by default.</p><p>That will not work, and is so subtle the error that you might fall for it as I did.</p><p>Do you see it? What is happening is that ‘datetime.now()’ is evaluated once (when models.py gets loaded) and not each time you need to create a new Book instance.</p><p>Here is the correct way:</p><pre># app/models.py<br>from django.db import models<br>from datetime import datetime</pre><pre>class Book(models.Model):<br>  name = models.CharField(max_length=128)<br>  release_date = models.DateTimeField(default=datetime.now)</pre><p>Yep. No parenthesis, now you are passing <strong>datetime.now</strong> <em>as callable </em>as default value, and <strong>datetime.now()</strong> will get invoked each time a Book is instantiated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e092e68fa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/current-datetime-for-default-value-in-a-model-use-callables-85e092e68fa6">Current DateTime for default value in a Model? Use callables</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django’s Hooks and Signals]]></title>
            <link>https://medium.com/django-musings/django-s-hooks-and-signals-6166369d798b?source=rss----b61cdf9ae3d6---4</link>
            <guid isPermaLink="false">https://medium.com/p/6166369d798b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hernán Tylim]]></dc:creator>
            <pubDate>Fri, 15 Apr 2016 20:52:37 GMT</pubDate>
            <atom:updated>2016-04-15T20:52:37.096Z</atom:updated>
            <content:encoded><![CDATA[<p>Django doc <a href="https://docs.djangoproject.com/en/1.9/topics/signals/">here</a>.</p><p>Sometimes you want to do something in your webapp as a response to an event that occurred elsewhere.</p><p>For instance. You might want that each time a model is saved to execute an action or update a different model.</p><p>You could refactor that logic in a method:</p><pre>class Book(models.Model):<br>  def increment_times_read(self):<br>    book.times_read += 1<br>    book.author.times_read += 1</pre><p>So every time that you need to increment <strong>times_read</strong> you use that method.</p><pre>b = Book.objects.get(id=123)<br>b.increment_times_read()</pre><p>But what happens if somewhere along the line we forget about the method and we change the field manually?</p><pre>b = Book.objects.get(id=123)<br>b.times_read = 3  # we do it manually</pre><p>If <strong>Author.times_read</strong> needs to have a corresponding value in Author then we are in a problem. (Yes this is a silly example and I am forcing the situation)</p><p>The way that you could make this happen automatically and also is clear is using hooks and signals (arrrhh matey -sorry, couldn’t avoid it)</p><h4>Hooks and Signals</h4><p>Django provides system signals that announce that something has happened in their system. One such signal is that a model has been saved.</p><p>The list of system signal is <a href="https://docs.djangoproject.com/en/1.9/ref/signals/">here</a>.</p><p>Also Django provides this framework for your app to create its own signals if you chose it so.</p><p>Hooks are the callables that you want to execute when a specified signal happened.</p><p>In this example we could say to Django to execute a method <strong>on_book_saved</strong> each time it saves a book so we could do what we need there.</p><h4>How to register a hook</h4><p>Django provides the receiver annotation to easily register automatically you do it this way:</p><pre># app/signals.py<br>from django.db.models.signals import post_save<br>from django.dispatch import receiver<br>from django.db import transaction</pre><pre>from .models import Book</pre><pre><a href="http://twitter.com/receiver">@receiver</a>(post_save, sender=Book)<br>def post_save_handler(sender, **kwargs):<br> book = kwargs.get(‘instance’, None)<br> created = kwargs.get(‘created’, False)<br> raw = kwargs.get(‘raw’, False)<br> …</pre><p>When the annotation “@receiver” is executed <strong>post_save_handler</strong> will be added automatically to the list of hooks to execute on such signal.</p><p>But of course that leaves us another problem. How can we force that annotation to be executed. Annotations will get executed by the interpreter when it loads the module. So how can we force to load this module at the start of our run?</p><p><strong>side note</strong>: It is customary to put all the hooks and signal declarations in a module called <strong>signals.py</strong>, you could choose something else but try to avoid coupling your signal logic with your model logic.</p><h4>The AppConfig.ready() method</h4><p>When django starts it looks for the <strong>AppConfig()</strong> instance of your application and executes its <strong>ready()</strong> method.</p><p>In this <strong>ready()</strong> method is where you do all your initialization.</p><p>This is how you implement your <strong>AppConfig.ready()</strong></p><pre># myapp/apps.py<br>from django.apps import AppConfig</pre><pre>class MyAppConfig(AppConfig):<br> name = “myapp”<br> label = “myapp”<br> verbose_name = “My App”</pre><pre>def ready(self):<br> # importing signal handlers<br> import myapp.signals</pre><p>So, you see. You subclass <strong>AppConfig</strong> and implement what you need. Doc <a href="https://docs.djangoproject.com/es/1.9/ref/applications/#django.apps.AppConfig">here</a>.</p><p><strong>note: </strong>you need to the very least implement those values of name and label. If you don’t you will get an error when you start your app.</p><p>Now that you implemented MyAppConfig you need to tell Django that <strong>that</strong> AppConfig is the one that represents your application. (if not it will use a default one that it has)</p><p>To do that in settings in INSTALLED_APPS you do include the path of that class:</p><pre>INSTALLED_APPS = [<br>  &#39;django.contrib.admin&#39;,<br>  ...<br>  &#39;myapp.apps.MyAppConfig&#39;]</pre><p><strong>Alternatively</strong> you could (and you should if you are using celery, but is for another article) overwrite <strong>default_app_config</strong> in your apps’ _init_.py</p><pre># myapp/_init_.py<br>default_app_config = &quot;myapp.apps.MyAppConfig&quot;</pre><p>And then your settings files remains unchanged:</p><pre>INSTALLED_APPS = [<br> ‘django.contrib.admin’,<br> …<br> ‘myapp’]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6166369d798b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-musings/django-s-hooks-and-signals-6166369d798b">Django’s Hooks and Signals</a> was originally published in <a href="https://medium.com/django-musings">Django Musings</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>