<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tobias Lorenz on Medium]]></title>
        <description><![CDATA[Stories by Tobias Lorenz on Medium]]></description>
        <link>https://medium.com/@tobias.lorenz?source=rss-489737af7f44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5FHJP6p8Ov1jibdQZioK5A.jpeg</url>
            <title>Stories by Tobias Lorenz on Medium</title>
            <link>https://medium.com/@tobias.lorenz?source=rss-489737af7f44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:30:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tobias.lorenz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Augment your Django project with Vue.js widgets]]></title>
            <link>https://medium.com/js-dojo/augment-your-django-project-with-vue-js-widgets-70e59effd2d3?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e59effd2d3</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 10:42:51 GMT</pubDate>
            <atom:updated>2019-04-05T10:42:51.688Z</atom:updated>
            <content:encoded><![CDATA[<p>We at <a href="https://bitlabstudio.com/">Bitlab Studio</a> love Django’s template language. It’s straightforward, has lots of ready-to-use features like i18n and built-in template tags and filters. Nevertheless using HTML/CSS/JS only limits your possibilities to create a fancy &amp; reactive application, especially if your project is backed by an API.</p><ul><li>Do you plan to build a beautiful single page application, but you have a tough deadline for the first prototype?</li><li>Do you have doubts about building a single page application at all?</li><li>Do you focus on fast results and functionality?</li><li>Do you simply want to enrich your Django app?</li></ul><p><em>Then I have something for you.</em></p><p><strong>tl;dr: </strong>Use Vue.js widgets to pimp your Django templates. Example:</p><pre>&lt;image-list&gt;&lt;/image-list&gt;<br>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>  Vue.component(&#39;image-list&#39;, {<br>    data: <strong>function </strong>() {<br>      <strong>return </strong>{<br>        images: [],<br>      }<br>    },<br>    template: `<br>      &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Images&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    `,<br>    beforeMount: <strong>function </strong>() {<br>      // Get images<br>      <strong>let </strong>el = <strong>this</strong>;<br>      axios(&#39;{% url &quot;api-user-images&quot; %}&#39;)<br>        .then(<strong>function</strong>(res) {<br>          el.images = res.data;<br>        });<br>    }<br>  });  <br>&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hxeJH_xJfyh2Ycn1" /><figcaption>Photo by <a href="https://unsplash.com/@nesabymakers?utm_source=medium&amp;utm_medium=referral">NESA by Makers</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There might be reasons though you don’t want to start with a single page application (“<em>SPA”</em>) right away. Especially when it comes to fast prototyping. Building a SPA can cause a lot of effort, especially regarding your deployment processes and you might head into the wrong direction. In contrast Django allows you to build up a strong prototype, which comes with a lot of basic features by default:</p><ul><li>Authentication</li><li>Forms and form field validation</li><li>ORM</li><li>Generic features like <a href="https://docs.djangoproject.com/en/2.1/topics/class-based-views/">class-based views</a></li><li><a href="https://docs.djangoproject.com/en/2.1/topics/i18n/">internationalization and localization</a></li></ul><p>If you plan to use an API, use <a href="https://www.django-rest-framework.org/">django-rest-framework</a> (REST) or <a href="https://github.com/graphql-python/graphene-django">graphene</a> (GraphQL), which are both very easy to implement.</p><blockquote>Hint: You can re-use your Django forms when using graphene :)</blockquote><p>As you know, adding the features mentioned above using a frontend frameworks takes some time. Setting up a Django prototype with basic functionality takes way less and is very flexible. Django and its features are so well-orchestrated that your prototype normally doesn’t need much code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XBI1LSXQak89VCZm" /><figcaption>Photo by <a href="https://unsplash.com/@pavel_kalenik?utm_source=medium&amp;utm_medium=referral">Pavel Kalenik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Time is money and being fast building a prototype is satisfying</h3><p>To demonstrate the efficiency of Django let’s plan tasks for a small app, which allows to upload images, assigns them to a user and shows them on the user’s profile.</p><ul><li>First, set up a Django project (<em>django-admin startproject mysite</em>)</li><li>Define a Django model, which stores an image and a user connection</li><li>Enable <a href="https://docs.djangoproject.com/en/2.1/topics/auth/#installation">authentication</a>, include the authentication <a href="https://docs.djangoproject.com/en/2.1/topics/auth/default/#module-django.contrib.auth.views">urls</a> and</li><li>Write a <a href="https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-editing/#createview">CreateView</a> , which displays the upload form</li><li>Add a template for the upload form</li><li>Add a <a href="https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-display/#detailview">DetailView</a> , which shows single users</li></ul><p>That’s it. Shouldn’t take an hour. The beauty in this is the flexibility. If you need more fields, just add them to the model and they will automatically appear in the form (and be automatically validated). If you need views to delete or update images, you can also add them with minimal effort using the class-based views.</p><p>I found this very helpful in times of early prototyping, when requirements and opinions change often.</p><h3>A prototype needs to thrill</h3><p>Building your prototype with Django is efficient, but the results are very basic. Your customers/friends/colleagues measure your prototype by current state-of-the-art applications. So we need to add some more magic. JavaScript magic. We don’t like redirects, we want AJAX calls. We want to store a state of the current components and make it easy to re-arrange/change/add/remove them. This fancy stuff is covered by several <a href="https://medium.com/cuelogic-technologies/top-3-best-javascript-frameworks-for-2019-3e6d21eff3d0">JS frameworks</a>.</p><p>Now we still want to make use of the fancy built-ins of Django, like authentication and translation. So why not combine the traditional superpowers of Django with the modern look-and-feel of JS?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DMZKCMVXMb4-0mmS" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What does that mean? It means using Django views, forms and templates and augment them with JavaScript widgets. By widgets I mean single components, which can be inserted into html templates.</p><p>At Bitlab Studio we normally prefer React. <a href="https://reactjs.org/">React</a> is powerful, but heavy. It is easy to set up a SPA, but you cannot simply insert React into Django templates. With <a href="https://vuejs.org/">Vue.js</a> you can. Without any setup.</p><p>If you want to build a SPA after your prototype has been reviewed and approved it’s easy to move the widgets you already created to the new SPA. So you actually don’t waste any time.</p><p>So now I’ll show you how to create Vue.js widgets and enrich them with all the beautiful Django features and vice versa.</p><h3>Synergy examples</h3><p>Let’s build a dashboard, which shows the current user’s images.</p><pre>from django.contrib.auth.models import User<br>from django.contrib.auth.decorators import login_required<br>from django.utils.decorators import method_decorator<br>from django.generic.views import DetailView</pre><pre>@method_decorator(login_required, name=&#39;dispatch&#39;)<br>class UserImagesView(DetailView):<br>    model = User</pre><pre>def get_object(self, *args, **kwargs):<br>        return self.request.user</pre><p>Using the authentication decorator you won’t have to care about the whole authentication workflow anymore.</p><p>Add the view to your urls.</p><pre>from django.conf import settings<br>from django.contrib import admin<br>from django.contrib.auth.views import LoginView, LogoutView<br>from django.conf.urls.static import static<br>from django.urls import path</pre><pre>from . import views</pre><pre>urlpatterns = [<br>    path(&#39;login/&#39;, LoginView.as_view(), name=&#39;login&#39;),<br>    path(&#39;logout/&#39;, LogoutView.as_view(), name=&#39;logout&#39;),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, views.DashboardView.as_view(), name=&#39;dashboard&#39;),<br>] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><p>Now create a basic template.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Of course, we could now use the Django templating language to show the images. But since we want to do fancy stuff and manipulate the DOM we can serve the content via Vue.js. Once we migrate to a SPA we can copy the components we already built.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;image-list&gt;&lt;/image-list&gt;<br>  &lt;/div&gt;</pre><pre>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    const app = new Vue({<br>      el: &#39;#app&#39;<br>    });</pre><pre>Vue.component(&#39;image-list&#39;, {<br>      data: <strong>function </strong>() {<br>        <strong>return </strong>{<br>          images: [<br>            {% for image in object.images.all %}<br>            { src: &#39;{{ image.src }}&#39;, alt: &#39;{{ image.alt }}&#39; }{% if not forloop.last %},{% endif %}<br>            {% endfor %}<br>          ]<br>        }<br>      },<br>      template: `<br>        &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>      `<br>    });  <br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>You see that? You can easily use Django’s template tags within your JS code.<br>You can, of course, already add some API calls, which makes it easier to move your Vue.js components into a SPA.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;image-list&gt;&lt;/image-list&gt;<br>  &lt;/div&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    const app = new Vue({<br>      el: &#39;#app&#39;<br>    });</pre><pre>Vue.component(&#39;image-list&#39;, {<br>      data: <strong>function </strong>() {<br>        <strong>return </strong>{<br>          images: []<br>        }<br>      },<br>      template: `<br>        &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>      `,<br>      beforeMount: <strong>function </strong>() {<br>        // Get images<br>        <strong>let </strong>el = <strong>this</strong>;<br>        axios(&#39;{% url &quot;api-user-images&quot; %}&#39;)<br>          .then(<strong>function</strong>(res) {<br>            el.images = res.data;<br>          });<br>      }<br>    });  <br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Sometimes Vue.js and Django syntax collide. Use the verbatim tag in that case to let Django ignore the contained code.</p><pre>{% verbatim %}<br>&lt;div v-if=&quot;image&quot;&gt;{{ image.src }}&lt;/div&gt;<br>{% verbatim %}</pre><p>You can also use the <a href="https://vuejs.org/v2/api/#delimiters">delimiters</a> setting. Thanks Raffaele for the <a href="https://twitter.com/blackpingus/status/1113121087372644354">hint</a>.</p><pre>new Vue({<br>  delimiters: [&#39;${&#39;, &#39;}&#39;]<br>})</pre><p>For forms you can use Django’s csrf_token tag.</p><pre>&lt;form id=&quot;form&quot; v-on:submit.prevent=&quot;submitForm&quot;&gt;<br>  {% csrf_token %}<br>  ...<br>&lt;/form&gt;<br>&lt;script&gt;<br>  function getCookie(name) {<br>    var cookieValue = null;<br>    if (document.cookie &amp;&amp; document.cookie !== &#39;&#39;) {<br>        var cookies = document.cookie.split(&#39;;&#39;);<br>        for (var i = 0; i &lt; cookies.length; i++) {<br>            var cookie = jQuery.trim(cookies[i]);<br>            // Does this cookie string begin with the name we want?<br>            if (cookie.substring(0, name.length + 1) === (name + &#39;=&#39;)) {<br>                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));<br>                break;<br>            }<br>        }<br>    }<br>    return cookieValue;<br>  }</pre><pre>const form = new Vue({<br>    el: &#39;#form&#39;,<br>    methods: {<br>      submitForm: function() {<br>        ...<br>        axios({<br>          url: &#39;/&#39;,<br>          method: &#39;post&#39;,<br>          headers: {&#39;X-CSRFToken&#39;: getCookie(&#39;csrftoken&#39;)},<br>          data: {what: &#39;ever&#39;}<br>        });<br>        ...<br>      }<br>    }<br>  });  <br>&lt;/script&gt;</pre><h3>But why?</h3><p>Every solution has its advantages, as well as disadvantages. The reason I personally like this approach is the speed, the flexibility and its pragmatism. I also love the convenience brought by frameworks, so I don’t want to miss any of them. I prefer to combine their powers instead, in one way or another.</p><p>If you have any questions, please leave a comment. If you think the reading was worth it, please leave some claps behind.</p><p>If you are located in Germany, let’s meet for a beer or coffee :) We love to meet new people. If you are too far away, say hello on <a href="https://twitter.com/askbitlabstudio">Twitter</a>!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e59effd2d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/augment-your-django-project-with-vue-js-widgets-70e59effd2d3">Augment your Django project with Vue.js widgets</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Augment your Django project with Vue.js widgets]]></title>
            <link>https://medium.com/bitlab-studio/augment-your-django-project-with-vue-js-widgets-8b18be7bd981?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b18be7bd981</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 11:55:24 GMT</pubDate>
            <atom:updated>2019-04-02T17:40:33.301Z</atom:updated>
            <content:encoded><![CDATA[<p>We love Django’s template language. It’s straightforward, has lots of ready-to-use features like i18n and built-in template tags and filters. Nevertheless using HTML/CSS/JS only limits your possibilities to create a fancy &amp; reactive application, especially if your project is backed by an API.</p><ul><li>Do you plan to build a beautiful single page application, but you have a tough deadline for the first prototype?</li><li>Do you have doubts about building a single page application at all?</li><li>Do you focus on fast results and functionality?</li><li>Do you simply want to enrich your Django app?</li></ul><p><em>Then I have something for you.</em></p><p><strong>tl;dr: </strong>Use Vue.js widgets to pimp your Django templates. Example:</p><pre>&lt;image-list&gt;&lt;/image-list&gt;<br>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>  Vue.component(&#39;image-list&#39;, {<br>    data: <strong>function </strong>() {<br>      <strong>return </strong>{<br>        images: [],<br>      }<br>    },<br>    template: `<br>      &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Images&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    `,<br>    beforeMount: <strong>function </strong>() {<br>      // Get images<br>      <strong>let </strong>el = <strong>this</strong>;<br>      axios(&#39;{% url &quot;api-user-images&quot; %}&#39;)<br>        .then(<strong>function</strong>(res) {<br>          el.images = res.data;<br>        });<br>    }<br>  });  <br>&lt;/script&gt;</pre><p>There might be reasons though you don’t want to start with a single page application (“<em>SPA”</em>) right away. Especially when it comes to fast prototyping. Building a SPA can cause a lot of effort, especially regarding your deployment processes and you might head into the wrong direction. In contrast Django allows you to build up a strong prototype, which comes with a lot of basic features by default:</p><ul><li>Authentication</li><li>Forms and form field validation</li><li>ORM</li><li>Generic features like <a href="https://docs.djangoproject.com/en/2.1/topics/class-based-views/">class-based views</a></li><li><a href="https://docs.djangoproject.com/en/2.1/topics/i18n/">internationalization and localization</a></li></ul><p>If you plan to use an API, use <a href="https://www.django-rest-framework.org/">django-rest-framework</a> (REST) or <a href="https://github.com/graphql-python/graphene-django">graphene</a> (GraphQL), which are both very easy to implement.</p><blockquote>Hint: You can re-use your Django forms when using graphene :)</blockquote><p>As you know, adding the features mentioned above using a frontend frameworks takes some time. Setting up a Django prototype with basic functionality takes way less and is very flexible. Django and its features are so well-orchestrated that your prototype normally doesn’t need much code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XBI1LSXQak89VCZm" /><figcaption>Photo by <a href="https://unsplash.com/@pavel_kalenik?utm_source=medium&amp;utm_medium=referral">Pavel Kalenik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Time is money and being fast building a prototype is satisfying</h3><p>To demonstrate the efficiency of Django let’s plan tasks for a small app, which allows to upload images, assigns them to a user and shows them on the user’s profile.</p><ul><li>First, set up a Django project (<em>django-admin startproject mysite</em>)</li><li>Define a Django model, which stores an image and a user connection</li><li>Enable <a href="https://docs.djangoproject.com/en/2.1/topics/auth/#installation">authentication</a>, include the authentication <a href="https://docs.djangoproject.com/en/2.1/topics/auth/default/#module-django.contrib.auth.views">urls</a> and</li><li>Write a <a href="https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-editing/#createview">CreateView</a> , which displays the upload form</li><li>Add a template for the upload form</li><li>Add a <a href="https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-display/#detailview">DetailView</a> , which shows single users</li></ul><p>That’s it. Shouldn’t take an hour. The beauty in this is the flexibility. If you need more fields, just add them to the model and they will automatically appear in the form (and be automatically validated). If you need views to delete or update images, you can also add them with minimal effort using the class-based views.</p><p>I found this very helpful in times of early prototyping, when requirements and opinions change often.</p><h3>A prototype needs to thrill</h3><p>Building your prototype with Django is efficient, but the results are very basic. Your customers/friends/colleagues measure your prototype by current state-of-the-art applications. So we need to add some more magic. JavaScript magic. We don’t like redirects, we want AJAX calls. We want to store a state of the current components and make it easy to re-arrange/change/add/remove them. This fancy stuff is covered by several <a href="https://medium.com/cuelogic-technologies/top-3-best-javascript-frameworks-for-2019-3e6d21eff3d0">JS frameworks</a>.</p><p>Now we still want to make use of the fancy built-ins of Django, like authentication and translation. So why not combine the traditional superpowers of Django with the modern look-and-feel of JS?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DMZKCMVXMb4-0mmS" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What does that mean? It means using Django views, forms and templates and augment them with JavaScript widgets. By widgets I mean single components, which can be inserted into html templates.</p><p>At Bitlab Studio we normally prefer React. <a href="https://reactjs.org/">React</a> is powerful, but heavy. It is easy to set up a SPA, but you cannot simply insert React into Django templates. With <a href="https://vuejs.org/">Vue.js</a> you can. Without any setup.</p><p>If you want to build a SPA after your prototype has been reviewed and approved it’s easy to move the widgets you already created to the new SPA. So you actually don’t waste any time.</p><p>So now I’ll show you how to create Vue.js widgets and enrich them with all the beautiful Django features and vice versa.</p><h3>Synergy examples</h3><p>Let’s build a dashboard, which shows the current user’s images.</p><pre>from django.contrib.auth.models import User<br>from django.contrib.auth.decorators import login_required<br>from django.utils.decorators import method_decorator<br>from django.generic.views import DetailView<br></pre><pre>@method_decorator(login_required, name=&#39;dispatch&#39;)<br>class UserImagesView(DetailView):<br>    model = User</pre><pre>    def get_object(self, *args, **kwargs):<br>        return self.request.user</pre><p>Using the authentication decorator you won’t have to care about the whole authentication workflow anymore.</p><p>Add the view to your urls.</p><pre>from django.conf import settings<br>from django.contrib import admin<br>from django.contrib.auth.views import LoginView, LogoutView<br>from django.conf.urls.static import static<br>from django.urls import path<br><br>from . import views<br><br>urlpatterns = [<br>    path(&#39;login/&#39;, LoginView.as_view(), name=&#39;login&#39;),<br>    path(&#39;logout/&#39;, LogoutView.as_view(), name=&#39;logout&#39;),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, views.DashboardView.as_view(), name=&#39;dashboard&#39;),<br>] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><p>Now create a basic template.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Of course, we could now use the Django templating language to show the images. But since we want to do fancy stuff and manipulate the DOM we can serve the content via Vue.js. Once we migrate to a SPA we can copy the components we already built.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;image-list&gt;&lt;/image-list&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    const app = new Vue({<br>      el: &#39;#app&#39;<br>    });</pre><pre>    Vue.component(&#39;image-list&#39;, {<br>      data: <strong>function </strong>() {<br>        <strong>return </strong>{<br>          images: [<br>            {% for image in object.images.all %}<br>            { src: &#39;{{ image.src }}&#39;, alt: &#39;{{ image.alt }}&#39; }{% if not forloop.last %},{% endif %}<br>            {% endfor %}<br>          ]<br>        }<br>      },<br>      template: `<br>        &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>      `<br>    });  <br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>You see that? You can easily use Django’s template tags within your JS code.<br>You can, of course, already add some API calls, which makes it easier to move your Vue.js components into a SPA.</p><pre>{% load i18n %}<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;{% trans &quot;Dashboard&quot; %}&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;image-list&gt;&lt;/image-list&gt;<br>  &lt;/div&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vue/dist/vue.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    const app = new Vue({<br>      el: &#39;#app&#39;<br>    });</pre><pre>    Vue.component(&#39;image-list&#39;, {<br>      data: <strong>function </strong>() {<br>        <strong>return </strong>{<br>          images: []<br>        }<br>      },<br>      template: `<br>        &lt;div&gt;<br>        &lt;h1&gt;{% trans &quot;Dashboard&quot; %}&lt;/h1&gt;<br>        &lt;ul v-cloak v-if=&quot;images.length&quot;&gt;<br>          &lt;li v-for=&quot;image in images&quot;&gt;<br>            &lt;img :src=&quot;image.src&quot; :alt=&quot;image.alt&quot; /&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>      `,<br>      beforeMount: <strong>function </strong>() {<br>        // Get images<br>        <strong>let </strong>el = <strong>this</strong>;<br>        axios(&#39;{% url &quot;api-user-images&quot; %}&#39;)<br>          .then(<strong>function</strong>(res) {<br>            el.images = res.data;<br>          });<br>      }<br>    });  <br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Sometimes Vue.js and Django syntax collide. Use the verbatim tag in that case to let Django ignore the contained code.</p><pre>{% verbatim %}<br>&lt;div v-if=&quot;image&quot;&gt;{{ image.src }}&lt;/div&gt;<br>{% verbatim %}</pre><p>You can also use the <a href="https://vuejs.org/v2/api/#delimiters">delimiters</a> setting. Thanks Raffaele for the <a href="https://twitter.com/blackpingus/status/1113121087372644354">hint</a>.</p><pre>new Vue({<br>  delimiters: [&#39;${&#39;, &#39;}&#39;]<br>})</pre><p>For forms you can use Django’s csrf_token tag.</p><pre>&lt;form id=&quot;form&quot; v-on:submit.prevent=&quot;submitForm&quot;&gt;<br>  {% csrf_token %}<br>  ...<br>&lt;/form&gt;<br>&lt;script&gt;<br>  function getCookie(name) {<br>    var cookieValue = null;<br>    if (document.cookie &amp;&amp; document.cookie !== &#39;&#39;) {<br>        var cookies = document.cookie.split(&#39;;&#39;);<br>        for (var i = 0; i &lt; cookies.length; i++) {<br>            var cookie = jQuery.trim(cookies[i]);<br>            // Does this cookie string begin with the name we want?<br>            if (cookie.substring(0, name.length + 1) === (name + &#39;=&#39;)) {<br>                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));<br>                break;<br>            }<br>        }<br>    }<br>    return cookieValue;<br>  }</pre><pre>  const form = new Vue({<br>    el: &#39;#form&#39;,<br>    methods: {<br>      submitForm: function() {<br>        ...<br>        axios({<br>          url: &#39;/&#39;,<br>          method: &#39;post&#39;,<br>          headers: {&#39;X-CSRFToken&#39;: getCookie(&#39;csrftoken&#39;)},<br>          data: {what: &#39;ever&#39;}<br>        });<br>        ...<br>      }<br>    }<br>  });  <br>&lt;/script&gt;</pre><h3>But why?</h3><p>Every solution has its advantages, as well as disadvantages. The reason I personally like this approach is the speed, the flexibility and its pragmatism. I also love the convenience brought by frameworks, so I don’t want to miss any of them. I prefer to combine their powers instead, in one way or another.</p><p>If you have any questions, please leave a comment. If you think the reading was worth it, please leave some claps behind.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b18be7bd981" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/augment-your-django-project-with-vue-js-widgets-8b18be7bd981">Augment your Django project with Vue.js widgets</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proper Unit Tests for Your Django Views]]></title>
            <link>https://medium.com/bitlab-studio/proper-unit-tests-for-your-django-views-b4a1730a922e?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a1730a922e</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mixin]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[views]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Mon, 11 Mar 2019 08:50:18 GMT</pubDate>
            <atom:updated>2019-03-11T08:50:18.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Often developers avoid writing tests like the plague. There are several reasons like tough deadlines, laziness, or <em>too much effort</em> for projects at early stages. If you want to avoid tests you’ll find an excuse. Anyway, writing tests can become frustrating if you are not used to it, if you are confronted with complex scenarios (e. g. mocking 3rd party SDKs or APIs) and if you aren’t well-prepared with your test setup in general.</p><p>Often developers and project managers/owners think it’s too time consuming, especially while working on prototypes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KGrNFfswqb2ostoc" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>It’s not</strong>, if you set up a decent test environment, which you can re-use on all projects.</p><p>As an example I’ll present a small mixin for views tests in Django, which makes use of the <a href="https://docs.djangoproject.com/en/2.1/topics/testing/advanced/#the-request-factory">RequestFactory</a> . Eventually your tests will be fast and convenient.</p><p><em>tl;dr: You’ll find a gist with the complete mixin at the end :)</em></p><h3>Test scenarios we want to cover</h3><p>Of course we want to build a mixin, which is easy to understand, extendible and which offers a lot of options to cover all test scenarios. Let’s define a list of requirements:</p><ul><li>GET calls with data</li><li>POST calls with data</li><li>Redirects</li><li>Different status codes</li><li>Logged in or anonymous users</li></ul><p>Let’s take a look at a typical test case for a simple GET request. I’ll make use of Django’s <a href="https://docs.djangoproject.com/en/2.1/topics/class-based-views/">generic class-based views</a> and call them directly.</p><pre><em>&quot;&quot;&quot;View test example.&quot;&quot;&quot;<br></em>from django.contrib.auth.models import AnonymousUser<br>from django.test import TestCase, RequestFactory<br><br>from . import views<br><br><br>class ExampleViewTestCase(TestCase):<br>    longMessage = True</pre><pre>    def test_get(self):<br>        status_code = 200<br>        view_class = views.ExampleView<br>        <br>        req = RequestFactory().get(&#39;/&#39;)<br>        req.user = AnonymousUser()<br>        resp = views.ExampleView.as_view()(req, *[], **{})<br>        self.assertEqual(resp.status_code, 200)</pre><p>As you can see the last four lines of this simple test case can be re-used for all views tests and the only dynamic variables are the view_class and the status_code .</p><p>So let’s build a mixin, which replaces those four lines with one shortcut.</p><pre><em>&quot;&quot;&quot;View test example.&quot;&quot;&quot;<br></em>from django.contrib.auth.models import AnonymousUser<br>from django.test import TestCase, RequestFactory<br><br>from . import views</pre><pre>class ViewRequestFactoryTestMixin(object):<br>    <em>&quot;&quot;&quot;Mixin with shortcuts for view tests.&quot;&quot;&quot;<br>    </em>longMessage = True  # More verbose messages<br>    view_class = None</pre><pre>    def get_response(self, method):<br>        factory = RequestFactory()<br>        req = getattr(factory, method)(&#39;/&#39;)<br>        req.user = AnonymousUser()<br>        return self.view_class.as_view()(req, *[], **{})</pre><pre>    def is_callable(self):<br>        resp = self.get_response(&#39;get&#39;)<br>        self.assertEqual(resp.status_code, 200)</pre><pre>class ExampleViewTestCase(ViewRequestFactoryTestMixin, TestCase):<br>    view_class = views.ExampleView<br>    <br>    def test_get(self):<br>        self.is_callable()</pre><p>First we create the very basic part of each view tests, the response object. Then we check the status code. Now it’s easy to enhance this mixin, e. g. for POST requests and for authenticated users. Can you already guess how?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52lAFUQNU2NqNY3u" /><figcaption>Photo by <a href="https://unsplash.com/@rizsam?utm_source=medium&amp;utm_medium=referral">Muhammad Rizwan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Yea, you are about to graduate. Let’s get it on.</p><pre>from django.contrib.auth.models import AnonymousUser<br>from django.http import Http404<br>from django.test import RequestFactory<br>from django.urls import resolve<br>from django.urls.exceptions import Resolver404<br></pre><pre>class ViewTestMixin(object):<br>    <em>&quot;&quot;&quot;Mixin with shortcuts for view tests.&quot;&quot;&quot;<br>    </em>longMessage = True  # More verbose error messages<br>    view_class = None<br><br>    def get_view_kwargs(self):<br>        <em>&quot;&quot;&quot;<br>        Returns a dictionary representing the view&#39;s kwargs, if  <br>        necessary.<br><br>        If the URL of this view is constructed via kwargs, you can <br>        override this method and return the proper kwargs for the <br>        test.<br><br>        &quot;&quot;&quot;<br>        </em>return {}<br><br>    def get_response(self, method, user, data, args, kwargs):<br>        <em>&quot;&quot;&quot;Creates a request and a response object.&quot;&quot;&quot;<br>        </em>factory = RequestFactory()<br>        req_kwargs = {}<br>        if data:<br>            req_kwargs.update({&#39;data&#39;: data})<br>        req = getattr(factory, method)(&#39;/&#39;, **req_kwargs)<br>        req.user = user if user else AnonymousUser()<br>        return self.view_class.as_view()(req, *args, **kwargs)<br><br>    def is_callable(<br>        self,<br>        user=None,<br>        post=False,<br>        to=None,<br>        data={},<br>        args=[],<br>        kwargs={},<br>    ):<br>        <em>&quot;&quot;&quot;Initiates a call and tests the outcome.&quot;&quot;&quot;<br>        </em>view_kwargs = kwargs or self.get_view_kwargs()<br>        resp = self.get_response(<br>            &#39;post&#39; if post else &#39;get&#39;,<br>            user=user,<br>            data=data,<br>            args=args,<br>            kwargs=view_kwargs,<br>        )<br>        if to:<br>            self.assertIn(resp.status_code, [301, 302],<br>                          msg=&#39;The request was not redirected.&#39;)<br>            name = resp.url.split(&#39;?&#39;)[0].split(&#39;#&#39;)[0]).url_name<br>            try:<br>                self.assertEqual(<br>                    resolve(name, to,<br>                    msg=&#39;Should redirect to &quot;{}&quot;.&#39;.format(to))<br>            except Resolver404:<br>                raise Exception(<br>                    &#39;Could not resolve &quot;{}&quot;.&#39;.format(resp.url))<br>        else:<br>            self.assertEqual(resp.status_code, 200)<br><br>    def is_not_callable(self, **kwargs):<br>        <em>&quot;&quot;&quot;Tests if call raises a 404.&quot;&quot;&quot;<br>        </em>with self.assertRaises(Http404):<br>            self.is_callable(**kwargs)</pre><p>Now the mixin already covers the following variations:</p><pre># GET<br>self.is_callable()</pre><pre># POST<br>self.is_callable(post=True)</pre><pre># Authenticated user<br>user = User.objects.create(username=&#39;Foo&#39;)<br>self.is_callable(user=user)</pre><pre># Redirect<br>self.is_callable(to=&#39;name_of_the_view_to_redirect_to&#39;)</pre><pre># Data<br>self.is_callable(data={&#39;foo&#39;: &#39;bar&#39;})<br>self.is_callable(post=True, data={&#39;foo&#39;: &#39;bar&#39;}, <br>                 to=&#39;view_name_of_success_url&#39;)</pre><pre># Different args<br>self.is_callable(args=[obj.pk])</pre><pre># Different kwargs<br>self.is_callable(kwargs={&#39;pk&#39;: obj.pk})</pre><p>Now you can easily extend this mixin for your purposes. For instance, you’ll likely add support for custom status codes or sessions.</p><p>Here’s a final test case for a typical update view.<br>Hint: I use <a href="https://github.com/klen/mixer">mixer</a> to easily instantiate objects :)</p><pre>class UpdateViewTestCase(ViewTestMixin, TestCase):<br>    <em>&quot;&quot;&quot;Tests for the `UpdateView` class.&quot;&quot;&quot;<br>    </em>view_class = views.UpdateView<br><br>    def setUp(self):<br>        self.obj = mixer.blend(&#39;app.Object&#39;)<br><br>    def get_view_kwargs(self):<br>        return {&#39;pk&#39;: self.obj.pk}<br><br>    def test_anonymous(self):<br>        self.is_callable(to=&#39;login&#39;)<br><br>    def test_get(self):<br>        self.is_callable(user=mixer.blend(&#39;auth.User&#39;))<br><br>    def test_post(self):<br>        self.is_callable(post=True, user=mixer.blend(&#39;auth.User&#39;),<br>                         data={&#39;name&#39;: &#39;Foo&#39;}, to=&#39;whatever&#39;)</pre><h3><strong>Hints for expansion</strong></h3><p>To simulate AJAX calls simply manipulate the meta data.</p><pre>req.META[&#39;HTTP_X_REQUESTED_WITH&#39;] = &#39;XMLHttpRequest&#39;</pre><p>To use sessions it’s a bit more complicated</p><pre># Enrich the request using the session middleware<br>middleware = SessionMiddleware()<br>middleware.process_request(req)<br>req.session.save()<br><br># Now you can add stuff to the session<br>req.session[&#39;burps&#39;] = &#39;worps&#39;</pre><p>You can also add <a href="https://docs.djangoproject.com/en/2.1/ref/contrib/messages/#django.contrib.messages.storage.fallback.FallbackStorage">messages support</a>.</p><pre>messages = FallbackStorage(req)<br>setattr(req, &#39;_messages&#39;, messages)</pre><p>That’s it. Here’s the final gist, my friends.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19d2fb5d775b53282b7e5fc310c813b2/href">https://medium.com/media/19d2fb5d775b53282b7e5fc310c813b2/href</a></iframe><p>I hope this makes testing a bit more fun. If you have any questions, please leave a comment. If you think the reading was worth it, please leave some claps behind.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a1730a922e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/proper-unit-tests-for-your-django-views-b4a1730a922e">Proper Unit Tests for Your Django Views</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beautiful A/B/n Testing with Google Analytics & Optimize]]></title>
            <link>https://medium.com/bitlab-studio/beautiful-a-b-n-testing-with-google-analytics-optimize-c33a4707cb17?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33a4707cb17</guid>
            <category><![CDATA[google-optimize]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 21:20:38 GMT</pubDate>
            <atom:updated>2019-01-16T21:20:38.429Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to a very short description how to create a proper A/B/n test for your website. A/B/n testing means to run experiments with two (<em>A and B</em>) or more (<em>n</em>) variants of your website or parts of it.</p><p>If you are already using a <a href="https://analytics.google.com/">Google Analytics</a> (<em>GA</em>) snippet on your website you might want to consider <a href="https://optimize.google.com/">Google Optimize</a> (<em>GO</em>), since it adds your experiments on top of everything you already track using GA.</p><p>If you haven’t set up your GA snippet you should <a href="https://support.google.com/analytics/answer/1042508">do it now</a>. Give it some time to breathe ;)</p><h3>Planning</h3><p>A typical scenario would be a different set of colours or texts followed by an expected action of the user. Of course, we want to know which variant leads to more conversions/clicks/page views/whatsoever.</p><p>Make sure to find out what you exactly want to achieve. Then navigate through your website and think of variants, which could effect your goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaiWScGKhDhaGK9EaRAklw.jpeg" /><figcaption>Two variants of the <a href="http://publishizer.com/">publishizer.com</a> website</figcaption></figure><p>In this example we want to reach more clicks on specific buttons throughout the website. We immediately thought of simple variants like:</p><ul><li>A different text (which means wording, which means a different call-to-action, which always has a strong effect on user behaviour)</li><li>A different button colour (people react differently to different-coloured areas or shapes)</li><li>A different background image (which is way more subtile, so you might want to leave this out to avoid unclear results or a wrong interpretation of those)</li></ul><h3>Groundwork</h3><p>If you are already tracking the expected action, you are done here. If not, you might want to set up conversion tracking or events in GA. Since we want to track clicks we’ll have to <a href="https://developers.google.com/analytics/devguides/collection/analyticsjs/events">add an event</a> to all buttons we would like to observe.</p><pre>&lt;a onclick=&quot;ga(&#39;send&#39;, &#39;event&#39;, &#39;Link&#39;, &#39;click&#39;, &#39;my_test&#39;);&quot; href=&quot;/&quot;&gt;Submit Your Idea&lt;/a&gt;</pre><p>See the onclick event? That’s it. See the last three arguments? You are free to define those and you can use them all in your GO experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnCZiGERvwm15KGFwgzqhQ.png" /><figcaption>Visit your real-time stats in GA to see who is clicking your buttons right now</figcaption></figure><h3>Set up your experiment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQEIjxVwoPJUUS2MTfk0Iw.jpeg" /></figure><p>Now we are ready to start with our experiment.</p><p>Go to Google Optimize and start with <em>Create Experiment.</em></p><p>Name it and add an editor page. This is the URL where you want to add your variants. For instance, add the URL on which you want to change a button colour.</p><p>Select your test type. If you have some spare time definitely check out all of them.</p><p>Click <em>Create</em> and you will be asked to complete your setup. On top you can always see what needs to be done.</p><p>Add a variant, edit it and be prepared to experience some fancy shit.</p><p>Stunning, right? GO uses the JS snippet on your website you added before to send data to GA and lets you add the variant right there. That’s so incredibly beautiful, smart and convenient. I was shocked.</p><p>Just click on the desired items, change them, remove them, do whatever you want to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*vmfc0pQszfLE9KXewkkI-A.jpeg" /></figure><p>Check out mobile and desktop layouts to make sure you don’t miss anything. Of course you can limit the tests to a specific group of people. The GA/GO powers combined are almighty :)</p><p>Using the A/B/n test you can modify stuff on the editor page only. If you want the same test on a different URL you’ll have to create a second test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQvjqmIT-rrOlAnATb2oxg.png" /><figcaption>Live editing on your website to create a variant</figcaption></figure><p>Regarding the targeting you need to define who takes part in your experiment. If you want to test all users and all pages, simply use URLs as parameters, add your base domain and consider all URLs, which start with your base domain (in other words: all URLs ;)).</p><p>Now you need to define an objective a.k.a. an action a.k.a. a goal. In our example we use a custom objective, based on an event. Now you can select one of the parameters you sent with the onclick event.</p><p>Please have a look at all options available and make sure you prepared your experiment to create your desired results. Finally start the whole thing and then… <strong>wait</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*EEvrqnvOuQjhlpFK5ZS2XQ.jpeg" /></figure><p>I recommend you check out the reporting shortly after your experiment has started to see if everything is working as expected. Please don’t end the experiment too early. Wait for the results to normalize, which might take 2–5 weeks.</p><p>Please don’t expect fast results using A/B/n testing, since you shouldn’t run too much tests parallel. Focus on your main issues or optimizations and try to establish A/B/n testing as a permanent optimization workflow. New experiments could be the result of your constant GA monitoring.</p><h3>Conclusion</h3><p>Google Optimize made A/B/n testing easy. Due to its friendly and supporting relationship with Google Analytics you don’t have to change much. You don’t need new snippets and you can be sure, that GA detects different users and don’t mess up your UX. And finally you don’t need to adjust your data policy, since you are not tracking additional data (<a href="https://en.wikipedia.org/wiki/General_Data_Protection_Regulation">GDPR</a> :)).</p><p>I hope your tests will help you to optimize your user journeys and to achieve your goals. If you have any questions, please leave a comment. If you think the reading was worth it, please leave some claps behind.</p><p>Thank you very much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33a4707cb17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/beautiful-a-b-n-testing-with-google-analytics-optimize-c33a4707cb17">Beautiful A/B/n Testing with Google Analytics &amp; Optimize</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Debugging]]></title>
            <link>https://medium.com/bitlab-studio/the-importance-of-debugging-886df73427ea?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/886df73427ea</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 08:21:00 GMT</pubDate>
            <atom:updated>2019-01-15T12:32:23.313Z</atom:updated>
            <content:encoded><![CDATA[<p>Being able to debug is a core skill for every developer. It separates the wheat from the chaff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQPIFSUJ6JTtZQpN4NwYvA.gif" /><figcaption><strong>Debugging</strong> is fun. This is some Django/Python code, debugged using PyCharm.</figcaption></figure><p>To effectively find and eliminate errors and bugs qualifies you for being responsible for a valuable product and a valuable team. In the end it increases your own value immensely, since you are a problem solver.</p><p><em>Disclaimer: </em>This article focuses on web development, specifically on apps written in Python and JavaScript.</p><h3>The general approach aka ‘trial and error’</h3><p>As a software consultant I often enter projects or companies, which don’t have any established debug workflows. Sometimes there’s no accountability policy at all. Hence issues might even be ignored completely.</p><p>If a developer is assigned to an issue it is often fixed by trying. You might have already guessed that this is the most ineffective approach to solve a problem.</p><p>So what comes first: Analysis.</p><h3>How to start</h3><p>Grab all the information you can get.<br>- Tracebacks<br>- Logging<br>- Screenshots<br>- Reports<br>If you are not able to identify the source of the issue you might already have a gap in your tool chain. Proper logging and reporting is a must to quickly identify the affected code.</p><p>Use tools like <a href="https://sentry.io/">Sentry</a>.</p><p>It’s always advisable to have a very simple workflow to reproduce errors. If possible, have a strong test and development environment, which includes tools for continuous integration.</p><p>We mainly use scripts (e. g. <a href="https://www.ansible.com/">Ansible</a> or <a href="http://www.fabfile.org/">Fabric</a>) to easily import the freshest data from the production server. Then we start with our analysis locally. There are also ways to debug on the server, but it’s way harder with less options.</p><h3>Profit from tools</h3><p>There are given parts in your tool chain, which are extremely helpful, if they are used in the right way.</p><p><em>Your IDE</em>: A properly set up editor is everything. It normally provides break points, code inspection, code linting, auto-completion, “go to” functionality, to move around quickly, and context while debugging. Choose your editor wisely.</p><p>Check out <a href="https://atom.io/">atom</a> or something from <a href="https://www.jetbrains.com/">JetBrains</a>.</p><p><em>Your browser</em>: Debugging on the frontend is quite easy using the developer tools for <a href="https://developers.google.com/web/tools/chrome-devtools/">Chrome</a> or <a href="https://developer.mozilla.org/de/docs/Tools">Firefox</a>. I will delve into that later.</p><h3>Backend assistance</h3><p>So, how can you easily prepare yourself for debugging in the backend? If you followed the recommendations above you’ll have a well-prepared editor and a project, which is able to spit out logs for everything, depending on the log level you defined. For example, if you are running a Django project in debug mode, you will receive a very clear traceback, once an exception is raised. In almost every case this will guide you directly to the broken part of your code.</p><p>Often issues aren’t based on exceptions, but more on unexpected results. In this case you definitely want to inspect the code, while it’s processed. Use your editor support or break point tools to stop at a certain point and check out the context, while being able to move forward, line by line. A beautiful break point tool for Python, for example, is <a href="https://pypi.org/project/ipdb/">ipdb</a> (which gives you more context and options than <a href="https://docs.python.org/3/library/pdb.html">pdb</a>, by the way).</p><h3>Frontend assistance</h3><p>Let’s focus on Chrome, since it has the widest variety of debug tools available.</p><p>In most cases static files are uglified and/or minified. To browse, understand and inspect frontend code you can unminify files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzxUj5HHynFDk_GrwxRYlQ.gif" /><figcaption>Live unminification of a <strong>Modernizr</strong> script.</figcaption></figure><p>Just open the file in the sources panel and hit the brackets icon.</p><p>Chrome offers beautiful ways to inspect and modify your code on-the-fly. Right-click the element you want to inspect or open the developer tools and see your source code, files, loading schedule and what not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_c3LkWRw92V-H8vPbI3Yw.gif" /><figcaption><strong>Inspecting</strong> a headline.</figcaption></figure><p>You should spend some time on reading the <a href="https://developers.google.com/web/tools/chrome-devtools/">docs</a> or checking out everything offered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yUUQMnjbkamU4-GRhPFuQ.png" /><figcaption>Testing layouts by using the device toolbar (blue highlighted icon on the lower left)</figcaption></figure><p>Running a responsive website creates unlimited layouts. You’ll use this tool every day.</p><p>Now when it comes to frontend, the main reasons you’ll have to debug are issues with styles and scripts. You are already able to play around with styles using the tools above. Since it’s trendy to create or own single page applications, let’s have a short excursion into the world of basic JavaScript helpers.</p><h3>JavaScript assistance</h3><p>The JS console is your friend. To simply output something use console.log(). This is a simple print of what’s in the brackets.</p><pre>console.log(&#39;foo&#39;);<br>&gt; &quot;foo&quot;<br>console.log(1 + 2);<br>&gt; 3</pre><p>To add a break point use debugger.</p><pre>function foo() {<br>  debugger;<br>  console.log(&#39;foo&#39;);<br>}<br>foo();</pre><p>As soon as the code is executed Chrome will stop right there. You can then proceed line by line, use the console and much more.</p><p>For a trace use console.trace. You will see a stacked output of the executed code.</p><pre>function foo() {<br>  console.trace();<br>}<br>function bar() {<br>  foo();<br>}<br>bar();</pre><p>You should see that bar was executed before foo.</p><p>Watch functions using monitor.</p><pre>function foo() {<br>  console.log(&#39;foo&#39;);<br>}<br>monitor(foo);<br>foo();</pre><p>It will let you know every time the monitored function is executed.</p><p>Debug functions using debug.</p><pre>function foo() {<br>  console.log(&#39;foo&#39;);<br>}<br>debug(foo);<br>foo();</pre><p>This is quite similar to debugger . Once the watched function is executed, Chrome will guide you to the code. Again you can then proceed line by line, use the console etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ficwm3MaQaRQ5LZkYe5PEA.gif" /><figcaption><strong>debug</strong> in action.</figcaption></figure><p>In general this should be enough to become a happy frontend debugging expert.</p><h3>Frameworks are extra</h3><p>Most frameworks provide additional and helpful tools. For example, in React there’s <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">React Developer Tools</a>, which lets you inspect state and components. For Angular you should check out this beautiful <a href="https://medium.com/front-end-hacking/a-guide-to-debugging-angular-applications-5a36bd88b4cf">article</a>.</p><p>The important part is to stay curious and to feel a constant urge to optimise your workflows.</p><h3>Conclusion</h3><p>Thinking and working effective and logical is something almost everybody can learn. It’s just a matter of discipline and training.</p><p>So debugging the right way will help you train your logical and analytical understanding, which, in my opinion, is the most important skill a developer can have. It helps you <em>wander</em> through code, understand the <em>matrix. </em>You’ll be fast and reliable and to others you’ll be the human interface to the app’s code and its relations.</p><p>This is the reason companies hire consultants. Consultants are expensive and they won’t stay within your company. Nevertheless they have been trained by a huge variety of projects to solve problems, and their products are results of all the knowledge and logic they gained. So finally consultants tend to be faster, a lot faster, if there’s a lack of effectiveness in the company’s debugging workflows. Saving time is equal saving money and companies need the most reliable product to reduce costs long term. So they hire someone who knows what could possibly go wrong. You only know the error-prone parts of software, if you were forced to debug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FzAIxStYaGTLs7qC" /><figcaption>“green and white maze illustration” by <a href="https://unsplash.com/@benjaminjohnelliott?utm_source=medium&amp;utm_medium=referral">Benjamin Elliott</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you want the most intense training as a developer, throw yourself into a pool of broken but highly active projects with short deadlines.</p><p>Let’s have a chat right after, we’re <a href="https://www.bitlabstudio.com/careers/">hiring</a> :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=886df73427ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/the-importance-of-debugging-886df73427ea">The Importance of Debugging</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Guide for Memory Monitoring on AWS/Ubuntu]]></title>
            <link>https://medium.com/bitlab-studio/easy-guide-for-memory-monitoring-on-aws-ubuntu-3e7fc16c89d3?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e7fc16c89d3</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 08:52:41 GMT</pubDate>
            <atom:updated>2019-05-08T06:46:07.506Z</atom:updated>
            <content:encoded><![CDATA[<p>We (<a href="https://bitlabstudio.com/">Bitlab Studio</a>) have had a few of our EC2 instances just drop dead in the middle of the night without any alert whatsoever. They weren’t restorable without stopping and starting, which always caused a reallocation of the IP and therefore a reconfiguration of the DNS settings, which sucks :)</p><p>We’ve already added some monitoring alerts and actions. For example, we <em>watch for abnormal network activity and reboot if it crossed a certain threshold</em>. However, we missed out on adding memory monitoring; which AWS doesn’t offer by default. Why? No clue.</p><p>Anyway, there’s a quite decent <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html">documentation</a> on how to set up a simple cron job. Since we always love to find compact <a href="https://blog.bitlabstudio.com/ultra-short-guide-to-django-and-amazon-s3-2c5aae805ce4">step-by-step guides</a> on the web, we’ve gone ahead and extracted all the necessary information, snippets and other required details to set this up. Let’s get started.</p><h3>Set up memory monitoring within 5 minutes</h3><ol><li>Install prerequisites. For Ubuntu do the following. For other OS see <a href="http://sudo apt-get update sudo apt-get install unzip sudo apt-get install libwww-perl libdatetime-perl">here</a>.</li></ol><pre>sudo apt-get update<br>sudo apt-get install unzip<br>sudo apt-get install libwww-perl libdatetime-perl</pre><p>2. Now proceed with the following commands, which will create a new folder under <strong>~/aws-scripts-mon/</strong>, which furthermore contains the monitoring scripts and other needed files.</p><pre>curl <a href="http://aws-cloudwatch.s3.amazonaws.com/downloads/CloudWatchMonitoringScripts-1.2.1.zip">http://aws-cloudwatch.s3.amazonaws.com/downloads/CloudWatchMonitoringScripts-1.2.1.zip</a> -O<br>unzip CloudWatchMonitoringScripts-1.2.1.zip<br>rm CloudWatchMonitoringScripts-1.2.1.zip<br>cd aws-scripts-mon<br>cp awscreds.template awscreds.conf</pre><p>3. Create or use an existing <a href="https://console.aws.amazon.com/iam">IAM</a> profile and add permissions for full access to <em>CloudWatch</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xb0SJggZORQCCxQEyvjb4w.png" /><figcaption>IAM profile permissions</figcaption></figure><p>4. Hit the security credentials tab and create a new access key. Copy the <strong>key</strong> and the <strong>secret</strong> and add it to <em>~/aws-scripts-mon/awscreds.conf/</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAILewLwdvUlEFyVKTadyg.png" /><figcaption>IAM security credentials</figcaption></figure><pre>nano awscreds.conf</pre><p>The file should look like this.</p><pre>AWSAccessKeyId=my-access-key-id<br>AWSSecretKey=my-secret-access-key</pre><p>Make sure to add the blank string without any quotation marks, backticks or apostrophes.</p><p>5. Test the monitoring command.</p><pre>/home/ubuntu/aws-scripts-mon/mon-put-instance-data.pl --mem-used-incl-cache-buff --mem-avail --mem-util --disk-space-util --disk-path=/</pre><p>You should receive a message like <em>Successfully reported metrics to CloudWatch. Reference Id: 12345</em>.</p><p>6. Add a <a href="https://en.wikipedia.org/wiki/Cron">cron job</a> to send data every 5 minutes (or whatever is suitable).</p><pre># Cloudwatch memory monitoring<br>*/5 * * * * /home/ubuntu/memory_monitor/aws-scripts-mon/mon-put-instance-data.pl --mem-used-incl-cache-buff --mem-avail --mem-util --disk-space-util --disk-path=/ &gt; $HOME/wherever/your/cron/logs/are/cloudwatch-memory-monitoring.log</pre><p>7. Go to the <em>CloudWatch</em> console and <a href="https://us-west-2.console.aws.amazon.com/cloudwatch/home">add a new alarm</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*j1VXr1JhZSi9gvol52ppIQ.png" /><figcaption>CloudWatch</figcaption></figure><p>The metric is listed below <em>Linux System Metrics</em> and <em>InstanceId</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yTj1vdCD3q7JoqmVngvRA.jpeg" /><figcaption>Select metric category</figcaption></figure><p>Now select the relevant metric. You should already see some data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUaCSBUOXoQ41K2qP40ZAw.jpeg" /><figcaption>Select metric</figcaption></figure><p>Add a name and a condition, which should trigger an alarm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnWGdBvcdxANs7KA0cWHIg.png" /></figure><p>Define actions like email notifications or a reboot. Whatever is suitable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8zIo9rc_leRhU-Jx_pUXw.jpeg" /><figcaption>Actions triggered by the alarm</figcaption></figure><p>That’s it. Your monitoring alarm is set! Check the monitoring once in a while to make sure the cron job is doing fine.</p><p>Got questions? Feel free to ask for help.</p><p>Want to know more about Bitlab Studio? Visit <a href="https://bitlabstudio.com/">bitlabstudio.com</a>!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e7fc16c89d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/easy-guide-for-memory-monitoring-on-aws-ubuntu-3e7fc16c89d3">Quick Guide for Memory Monitoring on AWS/Ubuntu</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Google Analytics API in Django / Python]]></title>
            <link>https://medium.com/bitlab-studio/using-the-google-analytics-api-in-django-python-3aea12f9e1d9?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aea12f9e1d9</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Fri, 05 May 2017 10:00:42 GMT</pubDate>
            <atom:updated>2019-05-08T06:54:49.784Z</atom:updated>
            <content:encoded><![CDATA[<p>The almighty Google API might be hard to understand. This is a guide for a fast and easy approach that we use at <a href="https://bitlabstudio.com/">Bitlab Studio</a> to get some data from your Google Apps in Python and/or Django.</p><p>We’re running several campaigns using <a href="https://support.google.com/analytics/answer/1033867?hl=en">utm parameters</a> and want to know how many times they were used and how successful they were by also receiving the conversation rate. Here’s an example link we use:</p><pre>https://example.com/?utm_medium=ad&amp;utm_source=facebook</pre><p>Let’s get it on. Install Google’s API client.</p><pre>pip install google-api-python-client==1.6.2</pre><h3>Prepare your Google account</h3><p>Now log in at Google and visit the <a href="https://console.developers.google.com/apis/library">Google API console</a>. Beautiful! All Google APIs at one place. Select the one you want to connect first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7CXBhSeK_MeTxl3TqrJRA.png" /><figcaption>API smorgasbord</figcaption></figure><p>In my example I will retrieve some <a href="https://console.developers.google.com/apis/api/analytics.googleapis.com/overview">Google Analytics stats</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*H6wcogkgW0n_uVTBwnJ4ng.png" /></figure><p>Enable the Analytics API. You can already see a nice dashboard, which will be filled with stats right after you started to use your API integration.</p><p>Since security is everything regarding your precious data we need to create some new credentials, which should only be used for this single purpose.</p><p>Visit the <a href="https://console.developers.google.com/iam-admin/serviceaccounts/project">Identity and Account Management</a> (IAM) and hit the <strong>Service account</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUBDK7Ie813kEXwaPgvMuQ.png" /></figure><p>Now you should create a new service account and name it after its purpose. I will name it <strong>Campaign stats</strong> since I want to get some GA campaign related stuff.</p><p>Make sure to create a JSON file, which includes a private key. You can also select a role to limit this user’s permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xA_mvZbDu3fkfRF89d2-wA.png" /></figure><p>The JSON file should be downloaded and you should be able to see the new service account listed in the IAM. Copy the <strong>service account ID</strong> (it’s an email address actually).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*byuB_tMT4DZ-sl-3w6y0Bg.png" /></figure><p>Now, open your <strong>Google Analytics account</strong> and check out the user management.</p><p>Add permissions for the service account ID, for example, <strong>Read &amp; Analyse</strong>.</p><p>You are now ready to request Google Analytics data via their API :)</p><h3>The python code</h3><p>Once you understand the structure and workflows of the Google API it becomes quite easy to handle. You’ll definitely have to rummage through the docs, so I’ll also provide you with all useful links.</p><p>I added a lot of comments to the code, which will let you know what’s going on in detail.</p><pre>import httplib2<br>import os<br><br>from apiclient.discovery import build<br>from oauth2client.service_account import ServiceAccountCredentials<br><br><br>def get_ga_metrics(medium=[&#39;ad&#39;], source=[&#39;facebook&#39;]):<br>    # Remember the JSON file you downloaded? We will use it now<br>    # for an ouath2 authentication. Be sure it&#39;s available on this<br>    # path. <br>    credentials = ServiceAccountCredentials.from_json_keyfile_name(<br>        os.path.join(os.path.dirname(__file__), <br>                     &#39;./WHATEVER_ITS_CALLED.json&#39;),<br>        &#39;https://www.googleapis.com/auth/analytics.readonly&#39;,<br>    )<br>    http = credentials.authorize(httplib2.Http())<br>    <br>    # The URL of the discovery service.<br>    DISCOVERY_URI = (<br>        &#39;https://analyticsreporting.googleapis.com/$discovery/rest&#39;)<br>    # Now we build the API connection. In that case we want to call <br>    # the &#39;analytics&#39; API version 4.<br>    analytics = build(<br>        &#39;analytics&#39;, &#39;v4&#39;, http=http, <br>        discoveryServiceUrl=DISCOVERY_URI)<br>    # Next we define the query we want to send to the API. There<br>    # are plenty of options. Link below. <br>    reports = analytics.reports().batchGet(<br>        body={<br>            &#39;reportRequests&#39;: [<br>                {<br>                    # The ID of your Analytics View. Cannot find it?<br>                    # Instructions below.<br>                    &#39;viewId&#39;: &#39;1234567&#39;,<br>                    &#39;dateRanges&#39;: [<br>                        {<br>                            &#39;startDate&#39;: &#39;2017-01-01&#39;,<br>                            &#39;endDate&#39;: &#39;2017-12-31&#39;,<br>                        },<br>                    ],</pre><pre>                    &#39;metrics&#39;: [<br>                        # This is where you define the data you want<br>                        # to receive. Link below. In this case I <br>                        # want the sessions count and the conversion <br>                        # rate<br>                        {&#39;expression&#39;: &#39;ga:sessions&#39;},<br>                        {&#39;expression&#39;: &#39;ga:transactionsPerVisit&#39;},<br>                    ],<br>                    &#39;dimensions&#39;: [<br>                        # Session attributes. We want to use our utm <br>                        # parameters, but you can also look for the<br>                        # user&#39;s country etc.<br>                        {&#39;name&#39;: &#39;ga:medium&#39;},<br>                        {&#39;name&#39;: &#39;ga:source&#39;},<br>                    ],<br>                    &quot;dimensionFilterClauses&quot;: [<br>                        # Let&#39;s add some filters for the Facebook<br>                        # ad campaign<br>                        {<br>                            &quot;filters&quot;: [<br>                                {<br>                                    &quot;dimensionName&quot;: &#39;ga:medium&#39;,<br>                                    &quot;operator&quot;: &#39;EXACT&#39;,<br>                                    &quot;expressions&quot;: medium,<br>                                },<br>                                {<br>                                    &quot;dimensionName&quot;: &#39;ga:source&#39;,<br>                                    &quot;operator&quot;: &#39;EXACT&#39;,<br>                                    &quot;expressions&quot;: source,<br>                                },<br>                            ],<br>                        }<br>                    ],<br>                }]<br>        }<br>    ).execute()<br>    <br>    # Google returns a huge dict. Let&#39;s extract all infos we need<br>    metrics = {}<br>    <strong>for </strong>row <strong>in </strong>reports[&#39;reports&#39;][0][&#39;data&#39;].get(&#39;rows&#39;, []):<br>        metrics[row[&#39;dimensions&#39;][1]] = {<br>            &#39;sessions&#39;: row[&#39;metrics&#39;][0][&#39;values&#39;][0],<br>            &#39;conversion_rate&#39;: row[&#39;metrics&#39;][0][&#39;values&#39;][1],<br>        }<br>    return metrics</pre><p>Here are the reporting options.</p><p><a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet">Method: reports.batchGet | Analytics Reporting API v4 | Google Developers</a></p><p>Looking for the View ID? Log in to your Analytics account, then select an <strong>account</strong>, a <strong>property</strong> a <strong>view</strong> and open the <strong>View Settings</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJ5705UkjKtLfawXToqHfQ.png" /></figure><p>There’s a nice tool to find out which data to add to your report.</p><p><a href="https://developers.google.com/analytics/devguides/reporting/core/dimsmets">Dimensions &amp; Metrics Explorer | Analytics Reporting API v4 | Google Developers</a></p><p>You also might want to play around with your queries to get the best results for your project.</p><p><a href="https://ga-dev-tools.appspot.com/query-explorer/">Query Explorer</a></p><p>As you can see there are already lot of options for the Analytics API only. Read their docs unhurriedly and you’ll easily find what you are searching for. That also applies for all of their APIs :)</p><p>Got questions? Feel free to ask for help.</p><p>Want to know more about Bitlab Studio? Visit <a href="https://bitlabstudio.com/">bitlabstudio.com</a>!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aea12f9e1d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/using-the-google-analytics-api-in-django-python-3aea12f9e1d9">Using the Google Analytics API in Django / Python</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using reCAPTCHA with Django]]></title>
            <link>https://medium.com/bitlab-studio/using-recaptcha-with-django-1b7aea786ad6?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b7aea786ad6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[captcha]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Tue, 11 Apr 2017 06:12:30 GMT</pubDate>
            <atom:updated>2019-05-08T06:55:48.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqPBrn4iAJbW23yJnMF7iw.png" /></figure><p>There are several ways to protect your forms from being submitted by impolite robots. Not long time ago we at <a href="https://bitlabstudio.com/">Bitlab Studio</a> mainly used the simple honeypot of a hidden field, which was accidentally filled out by every bot, who stumbled across our websites. If the request contained this field’s value we only simulated a successful form post.</p><p>But, as we know, even robots evolve, and suddenly those perky bots had the nerve to ignore this simple honeypot and submitted valid forms. It was time to move on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*zOSXjDuKBlLllU7TrYQG0Q.jpeg" /><figcaption>A comparatively easy example :)</figcaption></figure><p>We all know captchas can be frustrating. Since this is a guide I do not want to dig too deep in the history of captchas. But you all remember that strange malformed text images, which were a result of a race between captcha providers and bots. That was the reason we sticked to the easy solution mentioned above.</p><p>Anyway, Google came up with a nice solution, which doesn’t require any keyboard actions. Today I’ll help you to pretty up your Django forms.</p><h3>Let’s get it on</h3><p>First, let’s create a captcha instance at Google.</p><ul><li>Go to <a href="https://www.google.com/recaptcha/intro/invisible.html">https://www.google.com/recaptcha/</a></li><li>If necessary sign up or in</li><li>Add a name/label to your captcha and add all relevant domains (for testing purposes also add localhost, but be sure to remove it later)</li><li>You’ll see a key and a secret. Those will be added to your Django project later on</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Xog1HFY0Z7c4OCUDrMQPDw.png" /></figure><p>Install the awesome <a href="https://github.com/praekelt/django-recaptcha">django-recaptcha</a> and follow the instructions. Make sure to at least add the settings below.</p><pre>RECAPTCHA_PUBLIC_KEY = &#39;key&#39;<br>RECAPTCHA_PRIVATE_KEY = &#39;secret&#39;<br>NOCAPTCHA = True</pre><p>Now you can simply add the captcha field to a form.</p><pre>from django import forms<br>from django.conf import settings</pre><pre>from captcha.fields import ReCaptchaField</pre><pre><br>class ReCAPTCHAForm(forms.Form):<br>    captcha = ReCaptchaField()</pre><p>That’s it!</p><h3>Bonus: Enable submit button after captcha has been processed</h3><p>To avoid form submits without a valid captcha we can disable the form button.</p><pre>&lt;form method=&quot;post&quot; action=&quot;.&quot;&gt;<br>    {% csrf_token %}<br>    {{ form.as_p }}<br>    &lt;input type=&quot;submit&quot; id=&quot;recaptcha-submit&quot; disabled&gt;<br>&lt;/form&gt;</pre><p>Finally let’s overwrite django-recaptcha’s <a href="https://github.com/praekelt/django-recaptcha/blob/develop/captcha/templates/captcha/widget_nocaptcha.html">NOCAPTCHA</a> template and insert some extra code below the recaptcha api import.</p><pre>&lt;script type=&quot;text/javascript&quot;&gt;<br>    var DjangoRecaptchaOptions = {{options}};<br>    if (typeof RecaptchaOptions !== &#39;object&#39;) {<br>        RecaptchaOptions = DjangoRecaptchaOptions;<br>    } else {<br>        for (key in DjangoRecaptchaOptions) {<br>            RecaptchaOptions[key] = DjangoRecaptchaOptions[key];<br>        }<br>    }<br>    var recaptchaCallback = function(resp) {    <br>        document.getElementById(&quot;recaptcha-submit&quot;).disabled = false;<br>    };<br>    var recaptchaExpiredCallback = function(resp) { <br>        document.getElementById(&quot;recaptcha-submit&quot;).disabled = true; <br>    };<br>&lt;/script&gt;<br>&lt;div class=&quot;g-recaptcha&quot; data-sitekey=&quot;{{ public_key }}&quot; data-callback=&quot;recaptchaCallback&quot; data-expired-callback=&quot;recaptchaExpiredCallback&quot;&gt;&lt;/div&gt;</pre><h3>Bonus: Create a secured signup</h3><p>If you want to avoid bot signups, you can add the captcha to your authentication system.</p><p>You can create a custom authentication form, using Django’s <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm">built-in feature</a> or create a more enhanced solution by using <a href="https://github.com/pennersr/django-allauth">django-allauth</a>. I’ll show you how to customize your django-allauth integration.</p><p>Create a custom form, which inherits from the original signup form and proceed in the same way as described above.</p><pre>from allauth.account.forms import SignupForm</pre><pre>class CustomSignupForm(SignupForm):<br>    captcha = ReCaptchaField()</pre><p>Add the setting below.</p><pre>ACCOUNT_FORMS = {<br>    &#39;signup: &#39;myproject.forms.CustomSignupForm&#39;,<br>}</pre><p>Done!</p><h3>Super bonus: Looking ahead</h3><p>It’s getting even better. Google announced their invisible captcha solution some time ago, which doesn’t require any other user action than hitting the submit button itself. Therefore they directly attach the captcha actions to this button, which has to be part of the form anyway.</p><p>Give it a try! Just create a new captcha instance and select the invisible captcha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*WfuldZdOCrE48AcfCoysmw.png" /></figure><p>Now reduce the mentioned template to the following code and add <strong>recaptcha-form</strong> as the form’s ID.</p><pre>{% load i18n %}<br>&lt;script src=&#39;https://www.google.com/recaptcha/api.js{% if lang %}?hl={{ lang }}{% endif %}&#39;&gt;&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>    <strong>var </strong>recaptchaCallback = <strong>function</strong>(resp) {<br>      <strong>var </strong>form = document.getElementById(&quot;recaptcha-form&quot;);<br>      form.querySelectorAll(&#39;button&#39;).disabled = <strong>true</strong>;<br>      form.submit();<br>    };<br>&lt;/script&gt;<br>&lt;button class=&quot;btn btn-block btn-primary g-recaptcha&quot; data-sitekey=&quot;{{ public_key }}&quot; data-callback=&quot;recaptchaCallback&quot;&gt;{% trans &quot;Signup&quot; %}&lt;/button&gt;</pre><p>Got questions? Feel free to ask for help.</p><p>If you want to take a look at the invisible captcha in action please visit <a href="https://publishizer.com/accounts/signup/">publishizer.com</a> (alright, admittedly you won’t see much).</p><p>Want to know more about Bitlab Studio? Visit <a href="https://bitlabstudio.com/">bitlabstudio.com</a>!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b7aea786ad6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitlab-studio/using-recaptcha-with-django-1b7aea786ad6">Using reCAPTCHA with Django</a> was originally published in <a href="https://medium.com/bitlab-studio">Bitlab Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kurz gefasst: Anleitung für Django und Amazon S3]]></title>
            <link>https://medium.com/@tobias.lorenz/kurz-gefasst-anleitung-f%C3%BCr-django-und-amazon-s3-eb745afcf71f?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb745afcf71f</guid>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 21:58:19 GMT</pubDate>
            <atom:updated>2017-01-12T21:58:19.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Es mag zwei Gründe geben, dass du nun hier bist:<br>Entweder du folgst uns auf Medium, <a href="https://twitter.com/bitlab_studio">Twitter</a> oder <a href="https://www.facebook.com/bitlabstudiosg/">Facebook</a> (vielen Dank!) oder du suchst nach Wegen um dein Django-Projekt mit AWS S3 zu verknüpfen.</p><p>Wie dem auch sei, ich gehe davon aus, dass du mit Django an sich vertraut bist und du bereits von S3 gehört hast. Weiterhin gehe ich davon aus, dass du gerne in den praktischen Teil übergehen würdest. Na dann!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jWrMXHbEUyOMcHajh3NV7Q.png" /></figure><h3>Voraussetzungen</h3><p>Zunächst benötigen wir die aktuellen Versionen der Apps <a href="https://django-storages.readthedocs.io/en/latest/">django-storages</a> und <a href="https://boto3.readthedocs.io/en/latest/">boto3</a> (bitte ggfls. anpassen):</p><pre>django-storages==1.5.1<br>boto3==1.4.1</pre><h3>AWS Setup</h3><p>Erstelle einen <a href="https://aws.amazon.com/">AWS-Account</a>.</p><p>Besorge dir deine <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html">Zugangsdaten</a> vom <a href="https://console.aws.amazon.com/iam/home">AWS IAM</a> (Identity and Access Management):</p><ul><li>AWS Access Key ID</li><li>AWS Secret Access Key ID</li></ul><p>Nun kreiere einen S3-Bucket mit Hilfe der <a href="https://console.aws.amazon.com/s3/home">AWS S3 console</a> in deiner bevorzugten Zone.</p><h3>Settings</h3><pre># füge hier die Zugangsdaten vom IAM und den Namen des Buckets hinzu<br>AWS_STORAGE_BUCKET_NAME = &#39;mybucketname&#39;<br>AWS_ACCESS_KEY_ID = &#39;MEINEACCESSKEYID&#39;<br>AWS_SECRET_ACCESS_KEY = &#39;meinsecretaccesskey12345&#39;</pre><pre># falls &quot;False&quot;, werden eindeutige Dateinamen generiert<br>AWS_S3_FILE_OVERWRITE = False</pre><pre># die entsprechende URL für deine Dateien<br>AWS_S3_CUSTOM_DOMAIN = &#39;%s.s3.amazonaws.com&#39; % AWS_STORAGE_BUCKET_NAME</pre><pre># die Unterordner für Media- und Static-Files<br>STATICFILES_LOCATION = &#39;static&#39;<br>MEDIAFILES_LOCATION = &#39;media&#39;</pre><pre># eine modifizierte Storage-Klasse, um nur einen Bucket für Media- und Static-Files nutzen zu können<br>STATICFILES_STORAGE = &#39;myproject.custom_storages.StaticStorage&#39;<br>DEFAULT_FILE_STORAGE = &#39;myproject.custom_storages.MediaStorage&#39;</pre><pre># die regulären Django-File-Settings, aber versehen mit den entsprechenden S3-Links<br>STATIC_URL = &quot;https://%s/%s/&quot; % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)<br>MEDIA_URL = &quot;https://%s/%s/&quot; % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)</pre><h3>Die richtige Storage-Klasse</h3><p>Erstelle eine Datei namens custom_storages.py, welche bereits oben in den Settings definiert wurde und füge folgenden Code hinzu:</p><pre>from django.conf import settings</pre><pre>from storages.backends.s3boto3 import S3Boto3Storage</pre><pre><br>class StaticStorage(S3Boto3Storage):<br>    location = settings.STATICFILES_LOCATION</pre><pre>class MediaStorage(S3Boto3Storage):<br>    location = settings.MEDIAFILES_LOCATION</pre><h3>Das war’s!</h3><p>Nun führe den Befehl python manage.py collectstatic aus und, siehe da, alle Static-Files werden nach S3, in den entsprechenden Unterordner, kopiert.</p><p>Datei-Uploads werden in den Media-Unterordner hochgeladen.</p><h3>[OPTIONAL] Media-Files migrieren</h3><p>Installiere das AWS CLI auf deinem Server:</p><pre>$ sudo apt-get install awscli<br>$ aws configure</pre><pre># Zugangsdaten eingeben</pre><p>Kopiere die Dateien aus dem entsprechenden Media-Ordner:</p><pre>$ aws s3 cp /path/to/my/media s3://mybucketname/media --recursive --acl public-read-write</pre><h3>The end</h3><p>Vielen Dank für’s Lesen. Falls der Artikel dir eine Hilfe war, freuen wir uns sehr über ein Like oder ein Teilen.</p><p>Bei Fragen oder Problemen, schreib’ uns ein Kommentar und wir nehmen uns der Sache an.</p><p>Wohl bekomm’s!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb745afcf71f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eine Anleitung zur Nutzung von Braintree/PayPal und Django]]></title>
            <link>https://medium.com/@tobias.lorenz/eine-anleitung-zur-nutzung-von-braintree-paypal-und-django-ee7a2e71f67b?source=rss-489737af7f44------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7a2e71f67b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[paypal]]></category>
            <category><![CDATA[braintree]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Tobias Lorenz]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 19:10:51 GMT</pubDate>
            <atom:updated>2017-01-12T19:10:51.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOBCPOA7f8349ZO8kSEdXg.jpeg" /></figure><p>Es gab Zeiten, da brachte uns die Integration von automatisierten Bezahlungsprozessen in Django regelmäßig zur Weißglut. Es gab kaum Open-Source-Projekte und die wenigen waren kaum nutzbar oder mussten ständig den APIs angepasst werden, welche niemals stillstanden. In dieser Zeit begannen wir mit unserer ersten eigenen Bezahlungs-<a href="https://github.com/bitmazk/django-paypal-express-checkout">App</a>, und zwar für <a href="http://paypal.com/">PayPal</a>. Seitdem sind viele vielversprechende Anbieter auf den Markt gestoßen, unter ihnen <a href="https://stripe.com/">Stripe</a> und <a href="https://www.braintreepayments.com/">Braintree</a>.</p><p>Beide liefern heute hübsche und vielfältig nutzbare Lösungen und wir verwenden beide in unseren aktuellen Projekten. Heute stelle ich einen Leitfaden für unsere Braintree-Integration vor, welche seit Juni 2015 produktiv ist. Ich werde euch stark vereinfachten Code präsentieren, den ihr dann für eure Vorhaben erweitern könnt.</p><p>Zunächst solltet ihr euch vergewissern, dass Braintree euch und eure Unternehmung auch haben will :)</p><p><a href="https://www.braintreepayments.com/en-de/country-selection">Select your Country | Braintree Payments</a></p><p>Versucht Braintree direkt zu kontaktieren, um verbesserte Konditionen zu erhalten. Braintree unterstützt Startups und Großprojekte mit viel Zahlungsverkehr. Tipp: Schau mal nach Braintrees <a href="https://blueprint.paypal.com/">blueprint program</a>.</p><h3>Die Vorteile von Braintree</h3><p>Der Hauptvorteil ist die schiere Menge an Zahlungsarten. Dies ist bisher unerreicht. Braintree unterstützt:</p><ul><li>PayPal</li><li>Kredit- und Debitkarten</li><li>Bitcoin</li><li>Apple Pay</li><li>Android Pay</li><li>Venmo</li></ul><p><a href="https://www.braintreepayments.com/payment-methods">Payment Methods | Braintree Payments</a></p><p>Venmo und Braintree gehören zum PayPal-Konzern, somit können wir davon ausgehen, dass diese auch immer schön miteinander funktionieren werden. PayPal ist eine große Nummer in weltweiten Geldtransfers, besonders in der westlichen Welt bzw. in englischsprachigen Ländern. Braintree ist somit erste Wahl, falls du eine Möglichkeit suchst PayPal mit anderen Zahlungsarten einzubinden.</p><p><strong>Braintree bietet dir vorgefertigte Lösungen zur unmittelbaren Nutzung</strong></p><p>Wie auch immer dein Stack ausschaut, Braintree sollte bereits ein nettes SDK für dich in petto haben.</p><p>Auf der Nutzerseite:</p><ul><li>JavaScript (wird von uns genutzt und vorgestellt)</li><li>iOS</li><li>Android</li></ul><p>Und auf der Serverseite:</p><ul><li>Python (ist natürlich die richtige Wahl bei Django)</li><li>PHP</li><li>.NET</li><li>Java</li><li>Ruby</li><li>Node.js</li></ul><p>Wirf am besten einen Blick in die <a href="https://developers.braintreepayments.com/start/overview">Dokumentation</a>.</p><h3>Legen wir los</h3><p>Melde dich als erstes für einen <a href="https://signups.braintreepayments.com/">regulären</a> und einen <a href="https://www.braintreepayments.com/sandbox">Sandbox</a>-Account an. Um deinen Code zu testen nutzen wir zunächst den Sandbox-Account und seine entsprechenden API-Schlüssel. Später werde ich aufzeigen, wie du ganz einfach zwischen den Accounts hin und her wechselst, um deinen Live-Account sauber zu halten.</p><h3>Installieren des SDK</h3><p><a href="https://github.com/braintree/braintree_python">braintree/braintree_python</a></p><p>Oder gehe einfach wie folgt vor:</p><pre>pip install braintree</pre><p>Zur Zeit nutzen wir Version 3.33.0.</p><h3>Nun zum Code</h3><p>Wir müssen vier Bereiche bearbeiten: Settings, Forms, Views und Templates. Folgend zeige ich euch zunächst den kompletten Code, den ich dann stückweise kommentiere. Interessant sind vor allem die Kommentare im Code selbst. Diese habe ich für den internationalen Interessenten in Englisch gehalten.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea8756828205a98b6c82d9d078ebd28e/href">https://medium.com/media/ea8756828205a98b6c82d9d078ebd28e/href</a></iframe><p><strong>Vorbereitung des Zahlungsformulars<br></strong>Die Form hat nur einen simplen Zweck. Sie fügt dem Formular einen Identifier hinzu, welcher von Braintree zur Identifikation genutzt wird. Es ist das einzig notwendige Feld. Natürlich kann diese Form optional beliebig erweitert werden.</p><p><strong>Nun die View<br></strong>Wir verwenden Djangos <em>class-based views</em> um eine einfache <em>FormView</em> anzuzeigen. Die oben beschriebene View ist stark vereinfacht und dient dir als Vorlage für dein Projekt. Du wirst sie sicher erweitern wollen.</p><p>Die View hat nur drei einfache Aufgabe:</p><ul><li>Sie soll einen <em>client token</em> generieren (welcher mit Braintrees Skripten interagiert, um den Identifier zu kreieren)</li><li>Sie kreiert einen Braintree-Kundeneintrag</li><li>Sie kreiert eine Braintree-Transaktion</li></ul><p>Da es nicht immer nur von dir und deinem Code abhängig ist, ob eine Transaktion erfolgreich abgeschlossen werden kann (Kreditkarten können abgelehnt werden, kein Guthaben etc.), habe ich dem Code bereits diverse Fehlerberichte hinzugefügt.</p><p>Das war’s auch schon für den Backend-Code.</p><p><strong>Initiiere das Braintree Drop-In via JavaScript</strong><br>In meinem Beispiel verwende ich <a href="http://getbootstrap.com/">Bootstrap</a>, <a href="https://jquery.com/">jQuery</a> und <a href="http://requirejs.org/">RequireJS</a>. Natürlich musst du diese Tools nicht verwenden.</p><p>Ich empfehle die Nutzung des <a href="https://www.braintreepayments.com/products-and-features/drop-in-ui">Braintree Drop-Ins</a>, da es stets gepflegt wird und ein hübsches UI mitbringt.</p><h3>Durchforste Braintrees Dokumentation für weitere Möglichkeiten</h3><p>Braintree bietet viele weitere Objekte, Werkzeuge und Optionen, um den Zahlungsvorgang zu verschönern und dem Nutzer, aber auch dir gerecht zu werden.</p><p>Beispielsweise nutzen wir die API, um automatisiert Rückbuchungen anzustoßen und Kundendaten zu verwalten.</p><h3>Und wir sind durch!</h3><p>Du bist nun bereit den Geldsegen deiner Kunden zu empfangen und dein Projekt mit Unterstützung von Braintree zu optimieren.</p><p>Es gibt aber tatsächlich noch mehr zu tun. Du solltest Tests für deinen Code schreiben, falls nicht bereits geschehen (nicht vergessen die Requests zu mocken, andernfalls wirst du deine Sandbox mit Testdaten füllen) und sicherstellen alle Fehler zu erfassen und auszuwerten. Lass es mich wissen, falls ich solche Arbeiten in einem weiteren Artikel erläutern soll.</p><p>Ich bin offen für Fragen aller Art.<br>Falls du dir unsere Lösung anschauen möchtest: <a href="https://publishizer.com/">publishizer.com</a>.</p><p>Wohl bekomm’s!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7a2e71f67b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>