Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
The art of sharing nicks and descriptions
In the month or so since the merger of Evennia's development branch and all its web-client updates, we have been in bug-fixing mode as more people use and stress the code. There have been some new features as well though - I thought it could be interesting to those of you not slavishly following the mailing list. Shared web loginWhen you are logged into the website you will now also auto-login to your account in the web client - no need to re-enter the login information! The inverse is also true. You still need to connect to game at least once to create the account, but after that you will stay connected while the browser session lasts.Behind the scenes the shared login uses cookies linked to server-side Django sessions which is a robust and safe way to manage access tokens. Obviously browser sessions are irrelevant to telnet- or ssh connections.Extended Nicks Evennia's nick(name) system is a way to create a personal alias for things in game - both to on-the-fly replacing text you input and for referring to in-game objects. In the old implementation this replacement was simply matched from the beginning of the input - if the string matched, it was … -
Djangorecipe: easy test coverage reports
Code coverage reports help you see which parts of your code are still untested. Yes, it doesn't say anything about the quality of your tests, but at the least it tells you which parts of your code have absolute the worst kind of tests: those that are absent :-) Ned Batchelder's coverage.py is the number one tool in python. Note: I use buildout instead of pip to set up my projects. Reason: I can integrate extra automation that way. One of those extra automation steps is "djangorecipe": a recipe is a buildout plugin. It installs django, amongst others. My previous setup I use nose as a test runner. Easier test discovery was the reason at the time. Python's unittest2 is better at that, so it might be time to re-visit my choice. Especially as I just read that nose isn't really being maintained anymore. A nice thing about nose is that you can have plugins. coverage.py is a standard plugin. And with django-nose you can easily use nose as a test runner instead of the standard django one. So once I put a few nose-related settings in my setup.cfg, coverage was run automatically every time I ran my tests. Including … -
How to Use Django's Built-in Login System
Django comes with a lot of built-in resources for the most common use cases of a Web application. The registration app is a very good example and a good thing about it is that the features can be used out-of-the-box. With the Django registration app you can take advantages of the following features: Login Logout Sign up Password reset In this tutorial we will focus in the Login and Logout features. Getting started Before we start, make sure you have django.contrib.auth in your INSTALLED_APPS and the authentication middleware properly configured in the MIDDLEWARE_CLASSES settings. Both come already configured when you start a new Django project using the command startproject. So if you did not remove the initial configurations you should be all set up. In case you are starting a new project just to follow this tutorial, create a user using the command line just so we can test the login and logout pages. $ python manage.py createsuperuser In the end of this article I will provide the source code of the example with the minimal configuration. Configure the URL routes First import the django.contrib.auth.views module and add a URL route for the login and logout views: from django.conf.urls import … -
Two forms one view in django
This post is a reference for myself how to do a simple thing like rendering two forms in one view using django framework. How will it be working? The idea is very simple. There will be only one view to render both forms. Moreover, only GET method will be implemented to this view so there won't be a possibility to send POST request. Underneath the first main view will be 2 more views responsible only for handling POST request for both of forms. The simple picture presenting this can be seen below: Let's jump into the code. At first, there is main view responsible for rendering forms: class MainView(TemplateView): template_name = 'sample_forms/index.html' def get(self, request, *args, **kwargs): question_form = QuestionForm(self.request.GET or None) answer_form = AnswerForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['answer_form'] = answer_form context['question_form'] = question_form return self.render_to_response(context) This is simple TemplateView which is responsible only for GET request. At first, my setup question and answer form from the request. Right after that I add these forms to context dictionary and render them on sample_forms/index.html. My sample_forms/index.html looks as follows: <h1>Question Form</h1> <form action="{% url 'question' %}" method="post">{% csrf_token %} {{ question_form }} <input type="submit" value="Send Question"> </form> <h1>Answer Form</h1> … -
Two forms one view in django
This post is a reference for myself how to do a simple thing like rendering two forms in one view using django framework. How will it be working? The idea is very simple. There will be only one view to render both forms. Moreover, only GET method will be implemented to this view so there won't be a possibility to send POST request. Underneath the first main view will be 2 more views responsible only for handling POST request for both of forms. The simple picture presenting this can be seen below: Let's jump into the code. At first, there is main view responsible for rendering forms: class MainView(TemplateView): template_name = 'sample_forms/index.html' def get(self, request, *args, **kwargs): question_form = QuestionForm(self.request.GET or None) answer_form = AnswerForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['answer_form'] = answer_form context['question_form'] = question_form return self.render_to_response(context) This is simple TemplateView which is responsible only for GET request. At first, my setup question and answer form from the request. Right after that I add these forms to context dictionary and render them on sample_forms/index.html. My sample_forms/index.html looks as follows: <h1>Question Form</h1> <form action="{% url 'question' %}" method="post">{% csrf_token %} {{ question_form }} <input type="submit" value="Send Question"> </form> <h1>Answer Form</h1> … -
Two forms one view in django
Quick reference how to create two forms in one view using django. -
Django with Bash for Windows
Doing django development using "Bash for Windows" seems to work pretty well. See what it takes to set it up and get started.Watch Now... -
Mercurial Mirror For Django 1.10 branch
Following the recent 1.10-beta1 release, here is our usual “production” mirror, aimed at: being a lightweight read-only repository to clone from for production servers hide the ugly git stuff behind a great mercurial interface The clone is at the usual location at bitbucket, from which you can browse, clone, update, … https://bitbucket.org/orzel/django-1.10-production/ -
Python for OPS and platform teams - Pavel Chunyayev
(One of the talks at the 22 June 2016 Amsterdam Python meetup) The sub-title of his talk is supporting development teams in their journey to Continuous Delivery. Pavel's job description is continuous delivery architect. He loves biking so he just had to move to Amsterdam :-) What is continuous delivery? Often you'll hear something like "safely, rapidly and predictably deliver new features to production". But that's a little bit restricted. He likes to start already in the inception and planning stage and only end in the actual operation stage. So the whole process. You don't want to continuously deliver bad features that won't be used. You want to include the inception/planning stage to make sure the right features are implemented. A core idea is to keep the product releasable: build quality in. That is the core that we ought to remember. Quality is an integral part of the product, it is not something you can tack on later. So... quality in the entire build/test/release cycle. Build. All the checks you can do. Linting, static code analysis, unit tests. Test. Contract tests, end-to-end testsuites, browser tests, scaling tests. Release. Verify the deploy. Especially in the "test" phase, you need specific clean … -
A high availability Django setup on the cheap - Roland van Laar
(One of the talks at the 22 June 2016 Amsterdam Python meetup) Roland build an educational website that needed to be high available on a tight budget. He demoed the website. A site for the teacher on his own laptop and a separate page for on the digiboard for the class. The teacher steers the digiboard from his laptop (or an ipad or phone). As it is used in classrooms, it needs to be really really available. As a teacher, you don't want to have to change your lesson plan at 8:30. The customer hat three goals: Not expensive. Always up. Reliable. He had some technical goals of his own: Buildable. Functional. Maintainable. Always up? Django? You have the following challenges, apart from having a bunch of webservers. Media files. Files uploaded on one server need to be visible on others. Websockets. Database. Sessions. The setup he chose: Front end (html, javascript, images): cloudflare as CDN, content delivery network. The front end is a single page jquery app. It chooses a random API host for ajax requests. It changes API hosts when the API is not responding. But.... when is an API not responding? Some schools have really bad internet, … -
What are distributed systems? - Quazi Nafiul Islam
(One of the talks at the 22 June 2016 Amsterdam Python meetup) Distributed systems? Distributed computation (like hadoop, mapreduce). Distributed storage (like cassandra, riak). Distributed messaging (like kafka). You need distributed systems if you want to do more than is regulary possible. With many systems you need things like synchronisation (for instance NTP, network time protocol). A distributed system is a bunch of computers working together. Such systems have challenges and limitations. Take for instance the CAP theorem for distributed storage systems. You can't have all three of the following three at the same time: Consistency. Availability. Partition tolerance. You can for instance value availability over consistency. You give the answer as soon as possible, even if you're not completely sure you have the full answer (as other nodes might have extra/newer information). -
Query Expressions are Amazing
The Django 1.8 release added support for complex query expressions. The documentation has some nice examples but they don't do justice to how crazy awesome these are. In this post, we will go through some additional examples of how to leverage these expressions. Django has had one form of a query expression for several years now: the F expression. F() can be used to reference an existing column in a query. This is often used for atomic update operations, such as incrementing a counter. However, F can also be used to compare two columns on a model when filtering. For instance, we may be interested in users who haven't logged in since their first two weeks on the site. That requires comparing the value of the last_login column and the date_joined on the standard User model from contrib.auth: from datetime import timedelta from django.contrib.auth.models import User from django.db.models import F from django.utils.timezone import now # Create some fake data: 10 active users and 20 inactive ones today = now() active_count = 10 inactive_count = 20 for i in range(1, active_count + inactive_count + 1): active = i <= active_count prefix = 'in' if active else '' domain = 'example.com' if … -
The Journal of Medical Internet Research Features Epic Allies Phase 1 Study Results
The Journal of Medical Internet Research recently published “Epic Allies: Development of a Gaming App to Improve Antiretroviral Therapy Adherence Among Young HIV-Positive Men Who Have Sex With Men”. Epic Allies, initially funded by a federal Small Business Innovation Research (SBIR) grant, represents a partnership between Caktus, UNC’s Institute of Global Health and Infection Diseases, and Duke Global Health Institute. The article highlights the challenges of medication adherence, emphasizing the concerns of study participants directly: “Yeah, cause honestly, it was a good few months before I ever took medication. And in that timeframe of diagnosis to taking medication, it was very easy for me to detach. It was very easy for me to say, this is not real, nahhh, whatever. It didn’t become real until I had to take a pill. When you take a pill, it’s real.” - Study participant. The team used continuous participant feedback to iteratively develop the application. Ultimately, the study found that this iterative approach to application development was what made it “highly acceptable, relevant, and useful by YMSM (young men who have sex with men)”. The study authors are Sara LeGrand, PhD; Kathryn Elizabeth Muessig, PhD; Tobias McNulty, BA (Caktus); Karina Soni, BA; Kelly … -
The Philosophy of Channels
Why is Channels designed like it is, and what does it really mean for Django, Python, and WebSocket handling? It's been a while since my last blog post about Channels, and a lot has happened in the meantime - the API has developed out and stabilised, features like backpressure have come along, and the situation for backends is looking a lot better, especially once the local-and-remote combination layer matures some more. The other thing that has happened, however, is confusion and worry over the direction Channels is headed, and the direction it spells for Django and Python overall. A lot of the development of Channels was addressing and tackling my own personal worries with its direction, and picking the right set of tradeoffs, sometimes from two equally valid options. I've not been as proactive as I could have been at communicating my reasoning and long-term vision for what Channels could do; I'm hoping this blog post will rectify some of that. Let me take you through the specific set of problems I'm looking to tackle, why I chose to design things the way I did, and what I see as the path forwards. It's not just about WebSockets A lot … -
PyCon 2016 Recap
PyCon, beyond being the best community event for Python developers, is also an event that we happily began thinking about eleven months ago. Almost as soon as PyCon 2015 ended, we had the good fortune of planning the look and feel of PyCon 2016 with organizer extraordinaires Ewa Jodlowska, Diana Clark, and new this year, Brandon Rhodes. Our team has loved working with the organizers on the PyCon websites for the past three years now. They’re great people who always prioritize the needs of PyCon attendees, whether that’s babysitting services or a smooth PyCon web experience. Seeing the PyCon 2016 Artwork The Caktus team arrived in Portland and were almost immediately greeted with large-scale versions of the artwork our team made for PyCon. Seeing it on arrival, throughout the event, and especially during the keynotes was surreal. Getting ready for the tradeshow Our team got ready for the booth first, ahead of the PyCon Education Summit and Sponsor Workshops where we had team members speaking. Here’s the booth before everyone came to grab t-shirts and PyCon tattoos and to learn more about us. Here’s a closeup of our live RapidPro dashboard too. Supporting our team members This year, at the … -
My First Conference Talk: Reflecting on Support and Inclusivity at DjangoCon Europe 2016
The environment at Caktus is, above all, one of encouragement. I experienced that encouragement as an intern and continue to experience it as a full-time developer. In addition to providing workplace mentorship, Caktus encourages all of its employees to submit talks to conferences. My manager Mark Lavin and mentor Karen Tracy encouraged me to get over my concerns about being new to the field and to start submitting talks. Along with the support from Caktus was the impetus from Djangocon Europe for first-time speakers to submit. Djangocon Europe’s Call For Papers(CFP) includes suggested topics and offers of support beginning with brainstorming a topic and including mentors if your talk is chosen. I took them up on this offer and floated a couple of ideas over email. I got a very quick response with the suggestion that I expand a previous blog post I had written on my mid-career transition into a talk. Baptiste Mispelon and Xavier Dutreilh continued to be helpful and responsive throughout the application process and made me feel like my contribution was valued and that I was being taken seriously, whether my talk would be ultimately selected or not. A week later, I received the notification that … -
Ports and Adapters in python - part three
Next part of my application will be module for saving links to read them later. In the last post, I made a reddit search view for the specific keyword that display results to the user. To save them to read later I need database representation of link from reddit: from django.db import models class RedditLink(models.Model): title = models.CharField(max_length=250) is_favourite = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.is_favourite: super(RedditLink, self).save(*args, **kwargs) I made my own save because I only need links that are favorite in my database. In addition, I have multiple reddit links on my search page to save. So how to handle multiple forms of the same model in django? The answer is to use Fromset. What is it? It is module provided by django for creation multiple forms. How to use it? Look at forms.py: from django import forms from .models import RedditLink RedditAddToFavouritesFormset = forms.modelformset_factory( RedditLink, fields=('title', 'is_favourite'), extra=5 ) I used something called forms.modelformset_factory which is a function to produce fromset from model. So I provided model name with fields to calling this function. What is more, I add additional argument extra for creating more than one form in formset. How to use newly created RedditAddToFavouritesFormset? … -
Ports and Adapters in python - part three
Next part of my application will be module for saving links to read them later. In the last post, I made a reddit search view for the specific keyword that display results to the user. To save them to read later I need database representation of link from reddit: from django.db import models class RedditLink(models.Model): title = models.CharField(max_length=250) is_favourite = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.is_favourite: super(RedditLink, self).save(*args, **kwargs) I made my own save because I only need links that are favorite in my database. In addition, I have multiple reddit links on my search page to save. So how to handle multiple forms of the same model in django? The answer is to use Fromset. What is it? It is module provided by django for creation multiple forms. How to use it? Look at forms.py: from django import forms from .models import RedditLink RedditAddToFavouritesFormset = forms.modelformset_factory( RedditLink, fields=('title', 'is_favourite'), extra=5 ) I used something called forms.modelformset_factory which is a function to produce fromset from model. So I provided model name with fields to calling this function. What is more, I add additional argument extra for creating more than one form in formset. How to use newly created RedditAddToFavouritesFormset? … -
Ports and Adapters in python - part three
Third part of series about Django application made using Ports and Adapters design pattern. -
Custom python-social-auth Pipeline
Sometimes when you authenticate with a social service you need to do custom "stuff" in your code base beyond creating a user object. Learn how to get started simply adding a custom function do the python-social-auth pipeline.Watch Now... -
On Python 3, again
A while back, Brett Cannon went into some detail on why Python 3 happened (that is, why it was backwards-incompatible with Python 2 and why it was backwards-incompatible in the particular ways it was). Python 3 has been pretty controversial, with people I respect chiming in on both sides of the good idea/bad idea debate. And the transition (which Brett has also taken a recent look at) has indeed been slow, but that at ... Read full entry -
On Python 3, again
A while back, Brett Cannon went into some detail on why Python 3 happened (that is, why it was backwards-incompatible with Python 2 and why it was backwards-incompatible in the particular ways it was). Python 3 has been pretty controversial, with people I respect chiming in on both sides of the good idea/bad idea debate. And the transition (which Brett has also taken a recent look at) has indeed been slow, but that at ... Read full entry -
What We’re Clicking - May Link Roundup
Below you can find this month’s roundup of articles and posts shared by Cakti that drew the most attention on Twitter. The list covers coding for matrix factorization algorithms in Python, designing apps that optimize for sequential dual screen usage, preventing technical debt, and understanding the complexities and limitations involved in building apps for low-income American families. Finding Similar Music Using Matrix Factorization A step-by-step guide to calculating related music artists with matrix factorization algorithms. This tutorial is written in Python using Pandas and SciPy for calculations and D3.js for interactive data visualization. Windows on the Web Completing a task across multiple devices is a common habit. And yet, according to the author of this piece Karen McGrane, this practice is rarely considered in user design scenarios. In this article, McGrane contemplates how to design the best user experience for sequential dual screen usage. Technical Debt 101 This article is a detailed explanation of technical debt and the negative consequences of sacrificing code quality. What I Learned from Building an App for Low-Income Americans Ciara Byrne’s thoughtful article on lessons learned from her experience building an app for low-income Americans. Byrne reflects not only on the challenges involved in designing … -
Google Analytics Graphs to your Dashboard in Python Web Frameworks
Ecommerce solution providers like OpenCart, Magento Provide extensions to see Google analytics data in their own dashboards as graphs. whereas there are no such plugins availble in Python. In this tutorial, we will learn how to display google graphs in your website. Open Google Developers Console, Create a new project or open existing project. enable google analytics API. create a service account and generate a JSON Key File. Use the below function to generate access token for analytics in read only mode. Python: from oauth2client.client import SignedJwtAssertionCredentials import json def get_access_token(): ''' Get Access Token From GOOGLE''' SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' KEY_FILEPATH = <location to key file> with open(KEY_FILEPATH) as key_file: key_data = json.load(key_file) credentials = SignedJwtAssertionCredentials( key_data['client_email'], key_data['private_key'], SCOPE) return credentials.get_access_token().access_token you need to pass Google UserID and Google Acess Token to template. Javascript: //script to load analytics <script> (function(w,d,s,g,js,fs){ g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}}; js=d.createElement(s);fs=d.getElementsByTagName(s)[0]; js.src='https://apis.google.com/js/platform.js'; fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');}; }(window,document,'script')); </script> //script to show graphs <script> gapi.analytics.ready(function() { gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': "{{google_access_token}}" } }); var dataChart1 = new gapi.analytics.googleCharts.DataChart({ query: { 'ids': '{{google_userid}}', 'start-date': '30daysAgo', 'end-date': 'today', 'metrics': 'ga:sessions', 'dimensions': 'ga:date', 'sort': '-ga:date' }, chart: { 'container': 'chart-1-container', 'type': 'LINE', 'options': { 'width': '100%' } } }); dataChart1.execute(); //To change when selectbox value is … -
Ports and Adapters in python - part two
Last time I wrote about how to do simple port & adapter in python. In this post, I will show to actually use them. I briefly remind you what is purpose of application build in this series: user will log in, then search with keyword so he can save any search result to database for read it later. I decided to first implement search mechanism for Reddit. This is what I will write today. Search request will be sent via GET. First, I need some form to handle this: 1 from django import forms 2 from django.conf import settings 3 4 from external_api.external_api_port import instantiated_port 5 6 class RedditSearchForm(forms.Form): 7 query = forms.CharField(label='search query', max_length=100) 8 9 def perform_search(self): 10 search_result = instantiated_port.search(self.cleaned_data['query']) 11 return search_result I defined simple form that has only one field: query which is CharField field with label. My form has one method perform_search. In this method, I import instantiated reddit port that takes instance of reddit adapter with settings from django settings module. Idealy this adapter should be singleton class. This is how it looks in reddit_adapter: from django.conf import settings # reddit adapter class here ... instantiated_adapter = RedditAdapter( settings.REDDIT_CLIENT_ID, settings.REDDIT_CLIENT_SECRET, settings.REDDIT_USERNAME, settings.REDDIT_PASSWORD ) …