Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Kindle and ePub Now Available for Two Scoops of Django 1.11!
You asked for it, you got it. Two Scoops of Django 1.11 now comes in Kindle Mobi and ePub formats. If you've already purchased the PDF, you'll be receiving an email containing a new download link that adds the .mobi and .epub files. Otherwise, get yours at the following links: PDF/Kindle/ePub versions available here Amazon (Kindle only) -
Kindle and ePub Now Available for Two Scoops of Django 1.11!
You asked for it, you got it. Two Scoops of Django 1.11 now comes in Kindle Mobi and ePub formats. If you've already purchased the PDF, you'll be receiving an email containing a new download link that adds the .mobi and .epub files. Otherwise, get yours at the following links: PDF/Kindle/ePub versions available here Amazon (Kindle only) -
Kindle and ePub Now Available for Two Scoops of Django 1.11!
You asked for it, you got it. Two Scoops of Django 1.11 now comes in Kindle Mobi and ePub formats. If you've already purchased the PDF, you'll be receiving an email containing a new download link that adds the .mobi and .epub files. Otherwise, get yours at the following links: PDF/Kindle/ePub versions available here Amazon (Kindle only) -
Simple or fancy UPSERT in PostgreSQL with Django
As of PostgreSQL 9.5 we have UPSERT support. Technically, it's ON CONFLICT, but it's basically a way to execute an UPDATE statement in case the INSERT triggers a conflict on some column value. By the way, here's a great blog post that demonstrates how to use ON CONFLICT. In this Django app I have a model that has a field called hash which has a unique=True index on it. What I want to do is either insert a row, or if the hash is already in there, it should increment the count and the modified_at timestamp instead. The Code(s) Here's the basic version in "pure Django ORM": if MissingSymbol.objects.filter(hash=hash_).exists(): MissingSymbol.objects.filter(hash=hash_).update( count=F('count') + 1, modified_at=timezone.now() ) else: MissingSymbol.objects.create( hash=hash_, symbol=symbol, debugid=debugid, filename=filename, code_file=code_file or None, code_id=code_id or None, ) Here's that same code rewritten in "pure SQL": from django.db import connection with connection.cursor() as cursor: cursor.execute(""" INSERT INTO download_missingsymbol ( hash, symbol, debugid, filename, code_file, code_id, count, created_at, modified_at ) VALUES ( %s, %s, %s, %s, %s, %s, 1, CLOCK_TIMESTAMP(), CLOCK_TIMESTAMP() ) ON CONFLICT (hash) DO UPDATE SET count = download_missingsymbol.count + 1, modified_at = CLOCK_TIMESTAMP() WHERE download_missingsymbol.hash = %s """, [ hash_, symbol, debugid, filename, code_file or None, code_id or … -
Disabling Error Emails in Django
One of Django's nice "batteries included" features is the ability to send emails when an error is encountered. This is a great feature for small sites where minor problems would otherwise go unnoticed. Once your site start getting lots of traffic, however, the feature turns into a liability. An error might fire off thousands of emails in rapid succession. Not only will this put extra load on your web servers, but you could also take down (or get banned from) your email server in the process. One of the first things you want to do when setting up a high-traffic Django site is replace the default error email functionality with an error reporting service like Sentry. Once you've got Sentry setup, what's the best way to disable error emails? Unfortunately, there isn't one simple answer. Let's dig into why... How does Django Send the Emails? First let's look at how Django sends those emails. If you look at the source, you'll find it is defined in the default logging config using standard Python logging: 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', } As you can guess, the mail_admins handler is the one that does the work. It is defined as: … -
Disabling Error Emails in Django
One of Django's nice "batteries included" features is the ability to send emails when an error is encountered. This is a great feature for small sites where minor problems would otherwise go unnoticed. Once your site start getting lots of traffic, however, the feature turns into a liability. An error might fire off thousands of emails in rapid succession. Not only will this put extra load on your web servers, but you could also take down (or get banned from) your email server in the process. One of the first things you want to do when setting up a high-traffic Django site is replace the default error email functionality with an error reporting service like Sentry. Once you've got Sentry setup, what's the best way to disable error emails? Unfortunately, there isn't one simple answer. Let's dig into why... How does Django Send the Emails? First let's look at how Django sends those emails. If you look at the source, you'll find it is defined in the default logging config using standard Python logging: 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', } As you can guess, the mail_admins handler is the one that does the work. It is defined as: … -
Custom Analytics with Django
Analytics can make our service... -
The Almighty Pause Container
When checking out the nodes of your Kubernetes cluster, you may have noticed some containers called "pause" running when you do a `docker ps` on the node. $ docker ps CONTAINER ID IMAGE COMMAND ... ... 3b45e983c859 gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... dbfc35b00062 gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... c4e998ec4d5d gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... 508102acf1e7 gcr.io/google_containers/pause-amd64:3.0 "/pause[...] -
The Almighty Pause Container
When checking out the nodes of your Kubernetes cluster, you may have noticed some containers called "pause" running when you do a `docker ps` on the node. $ docker ps CONTAINER ID IMAGE COMMAND ... ... 3b45e983c859 gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... dbfc35b00062 gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... c4e998ec4d5d gcr.io/google_containers/pause-amd64:3.0 "/pause" ... ... 508102acf1e7 gcr.io/google_containers/pause-amd64:3.0 "/[...] -
A Complete Beginner's Guide to Django - Part 6
Introduction Welcome to the sixth part of the tutorial series! In this tutorial, we are going to explore in great detail the Class-Based Views. We are also going to refactor some of the existing views so to take advantage of the built-in Generic Class-Based Views. There are many other topics that we are going to touch with this tutorial, such as how to work with pagination, how to work with Markdown and how to add a simple editor. We are also going to explore a built-in package called Humanize, which is used to give a “human touch” to the data. Alright, folks! Let’s implement some code. We have plenty of work to do today! Views Strategies At the end of the day, all Django views are functions. Even class-based views (CBV). Behind the scenes, it does all the magic and end-up returning a view function. Class-based views were introduced so to make it easier for developers to reuse and extend views. There are many benefits of using them, such as the extendability, the ability to use O.O. techniques such as multiple inheritances, the handling of HTTP methods are done in separate methods, rather than using conditional branching, and there are … -
How to Create a Custom Django User Model
Django's built-in User model a... -
The Simple Power of Django Validators
# The Simple Power of Django V... -
Upgrade All Pip & Python Packages & Store an Archive
This guide is still being deve... -
Docker-compose in Jenkins pipelines: keep builds separate
We use Jenkins with the pipelines plugin as our continuous integration server to test our software. The pipelines plugin means all the steps are in a Jenkinsfile inside your repo instead of as manually entered commands in a web interface (like it used to be). Nice and clean. Also nice and clean: using dockers (with docker-compose) to run the tests in. The Jenkins machine used to be one big huge mess of installed software. Now it is clean and tidy: everything you need to run tests, you'd better install it inside your docker. Recent problem. Recently Jenkins changed the "workspace" location: the place where the project is checked out and where your docker-compose is run. It used to be /var/lib/jenkins/workspaces/longdirectoryname. "longdirectoryname" would include (abbreviated) your project's name, your branch/PR's name and some hash. Any networks/volumes/etc created by docker-compose would include that unique name. Recently, that location became /var/lib/jenkins/jobs/ORG_NAME/jobs/PROJECT_NAME/... and some more, ending with .../workspace. So suddenly every build is inside a directory called workspace so docker-compose will by default start prefixing networks/volumes with workspace instead of with a string that's unique per project/branch! So if you run a branch and pull request at the same time, both docker-compose runs will … -
A Complete Beginner's Guide to Django - Part 5
Introduction Welcome to the 5th part of the tutorial series! In this tutorial, we are going to learn more about protecting views against unauthorized users and how to access the authenticated user in the views and forms. We are also going to implement the topic posts listing view and the reply view. Finally, we are going to explore some features of Django ORM and have a brief introduction to migrations. Protecting Views We have to start protecting our views against non-authorized users. So far we have the following view to start new posts: In the picture above the user is not logged in, and even though they can see the page and the form. Django has a built-in view decorator to avoid that issue: boards/views.py (view complete file contents) from django.contrib.auth.decorators import login_required @login_required def new_topic(request, pk): # ... From now on, if the user is not authenticated they will be redirected to the login page: Notice the query string ?next=/boards/1/new/. We can improve the log in template to make use of the next variable and improve the user experience. Configuring Login Next Redirect templates/login.html (view complete file contents) <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next … -
Evennia in Hacktoberfest 2017
Evennia, the Python MUD/MUSH/MU* creation library participates in the Hacktoberfest 2017 (sign up on that page)! Hacktoberfest is open for all open-source projects like ours. After registering, if you make at least four Pull Requests to a public repo on Github during October (need not just be to Evennia), you win a limited-edition T-shirt! The help Evennia out and get your T-Shirt, look at our Issue Tracker. I have marked some issues with "Hacktoberfest" but you could take on any issue you want. Take a look in particular at the Unit test issue if you are looking to get into contributing on a smaller scale while helping us tremendously.If you have any questions on contributing (or it's your first time making a Pull Request), don't be shy to drop into #evennia on irc.freenode.net or ask in our forum/mailing list. Have fun! -
Numbers in Translatable Strings
Sentences in websites like "You've got 1 messages." or "Messages you've got: 5" sound unnatural and not human-friendly. But the GNU gettext tool used with Django for translations has an option to define different pluralization depending on the number which goes together with the counted noun. Things get even more interesting with certain languages which have not just singular and plural like English, German, French, or Spanish, but more plural forms or just a single one. Tell me the background Let's talk about grammar. Most languages have two plural forms for counted elements: one for singular, like "1 thing", and one for plural, like "n things". However, certain languages have either just one form for singular and plural, or multiple plural forms depending on the number of elements that go with them. For example, my mother tongue Lithuanian is a Baltic language coming from Indo-European language family keeping archaic features from ancient Sanskrit. Lithuanian has 3 plural forms. When one counts apples in Lithuanian, they say "1 obuolys", "2-9 obuoliai", "10-20 obuolių", "21 obuolys", "22-29 obuoliai", "30 obuolių", "31 obuolys", "32-39 obuoliai", etc. The second most widespread language on the web after English is Russian. Russian is an Eastern Slavic … -
How to Create Django Data Migrations
Data Migration is a very convenient way to change the data in the database in conjunction with changes in the schema. They work like a regular schema migration. Django keep track of dependencies, order of execution and if the application already applied a given data migration or not. A common use case of data migrations is when we need to introduce new fields that are non-nullable. Or when we are creating a new field to store a cached count of something, so we can create the new field and add the initial count. In this post we are going to explore a simple example that you can very easily extend and modify for your needs. Data Migrations Let’s suppose we have an app named blog, which is installed in our project’s INSTALLED_APPS. The blog have the following model definition: blog/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=255) date = models.DateTimeField(auto_now_add=True) content = models.TextField() def __str__(self): return self.title The application is already using this Post model; it’s already in production and there are plenty of data stored in the database. id title date content 1 How to Render Django Form Manually 2017-09-26 11:01:20.547000 […] 2 How to Use Celery … -
A Complete Beginner's Guide to Django - Part 4
Introduction This tutorial is going to be all about Django’s authentication system. We are going to implement the whole thing: registration, login, logout, password reset, and password change. You are also going to get a brief introduction on how to protect some views from non-authorized users and how to access the information of the logged in user. In the next section, you will find a few wireframes of authentication-related pages that we are going to implement in this tutorial. After that, you will find an initial setup of a new Django app. So far we have been working on an app named boards. But all the authentication related stuff can live in a different app, so to achieve a better organization of the code. Wireframes We have to update the wireframes of the application. First, we are going to add new options for the top menu. If the user is not authenticated, we should have two buttons: sign up and log in. Figure 1: Top menu for not authenticated users. If the user is authenticated, we should instead display their names along with a dropdown menu with three options: my account, change password and log out. Figure 2: Top menu … -
Evennia 0.7 released
As of today Evennia 0.7 is officially out! A big thank you to all collaborators that have helped with code and testing along the way!Here is the hefty forum post that details how you migrate to Evennia 0.7. Evennia 0.7 comes with a range changes and updates (these are just the ones merged from the latest devel branch, a lot more has happened since 0.6 that were already in master): EvMenu formatting functions now part of class - EvMenu no longer accepts formatting functions as inputs, these are now part of the EvMenu class. To override the formatting of EvMenu nodes you should now override EvMenu and replace the format method you want. This brings EvMenu more in line with other services in Evennia, all of which are built around overriding.Scripts are now valid message senders - Also Scripts can now act as "sender" of a Msg, for example to a Channel or a player.Prefix-ignoring - All default commands are now renamed without their @-prefixes. Both @examine, +examine or examine will now all point to the same command. You can customize which prefixes Evennia simply ignores when searching for a command. The mechanic is clever though - if you create … -
A Complete Beginner's Guide to Django - Part 3
Introduction In this tutorial, we are going to dive deep into two fundamental concepts: URLs and Forms. In the process, we are going to explore many other concepts like creating reusable templates and installing third-party libraries. We are also going to write plenty of unit tests. If you are following this tutorial series since the first part, coding your project and following the tutorial step by step, you may need to update your models.py before starting: boards/models.py class Topic(models.Model): # other fields... # Add `auto_now_add=True` to the `last_updated` field last_updated = models.DateTimeField(auto_now_add=True) class Post(models.Model): # other fields... # Add `null=True` to the `updated_by` field updated_by = models.ForeignKey(User, null=True, related_name='+') Now run the commands with the virtualenv activated: python manage.py makemigrations python manage.py migrate Or if you prefer to use my source code as a starting point, you can grab it on GitHub. The current state of the project can be found under the release tag v0.2-lw. The link below will take you to the right place: https://github.com/sibtc/django-beginners-guide/tree/v0.2-lw The development will follow from here. URLs Proceeding with the development of our application, now we have to implement a new page to list all the topics that belong to a given Board. … -
Blue/Green Deployments on Kubernetes
> For those that want to dive right in, I have put up a tutorial and some sample manifests on github. Check it out at https://github.com/IanLewis /kubernetes-bluegreen-deployment-tutorial Kubernetes has a really awesome built-in feature called Deployments. Deployments come with the ability to do rolling updates of containers when you update your application to a new version. Rolling updates are a great way to update applications because your app uses about the same amount of resources during an update as it does when not updating, all with minimal impact to performance and availability. [...] -
Blue/Green Deployments on Kubernetes
> For those that want to dive right in, I have put up a tutorial and some > sample manifests on github. Check it out at > https://github.com/IanLewis/kubernetes-bluegreen-deployment-tutorial Kubernetes has a really awesome built-in feature called Deployments. Deployments come with the ability to do rolling updates of containers when you update your application to a new version. Rolling updates are a great way to update applications because your app uses about the same amount of resources during an update as it does when not updating, all with minimal impact to performance and availabilit[...] -
Multitenancy: juggling customer data in Django
Suppose you want to build a new SaaS (Software as a Service) application. Suppose your application will store sensitive data from your customers. What is the best way to guarantee the isolation of the data and make sure information from one client does not leak to the other? The answer to that is: it depends. It depends on the number of customers y -
cache_memoize - a pretty decent cache decorator for Django
This is something that's grown up organically when working on Mozilla Symbol Server. It has served me very well and perhaps it's worth extracting into its own lib. Usage Basically, you are probably used to this in Django: from django.core.cache import cache def compute_something(user, special=False): cache_key = 'meatycomputation:{}:special={}'.format(user.id, special) value = cache.get(cache_key) if value is None: value = _call_the_meat(user.id, special) # some really slow function cache.set(cache_key, value, 60 * 5) return value Here's instead how you can do exactly the same with cache_memoize: from wherever.decorators import cache_memoize @cache_memoize(60 * 5) def compute_something(user, special=False): return _call_the_meat(user.id, special) # some really slow function Cache invalidation If you ever need to do non-trivial caching you know it's important to be able to invalidate the cache. Usually, to be able to do that you need to involved in how the cache key was created. Consider our two examples above, here's first the common thing to do: def save_user(user): do_something_that_will_need_to_cache_invalidate(user) cache_key = 'meatycomputation:{}:special={}'.format(user.id, False) cache.delete(cache_key) # And when it was special=True cache_key = 'meatycomputation:{}:special={}'.format(user.id, True) cache.delete(cache_key) This works but it involves repeating the code that generates the cache key. You could extract that into its own function of course. Here's how you do it with …