Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Automating Dokku Setup with AWS Managed Services
Dokku is a great little tool. It lets you set up your own virtual machine (VM) to facilitate quick and easy Heroku-like deployments through a git push command. Builds are fast, and updating environment variables is easy. The problem is that Dokku includes all of your services on a single instance. When you run your database on the Dokku instance, you risk losing it (and any data that's not yet backed up) should your VM suddenly fail. -
A Complete Beginner's Guide to Django - Part 7
Introduction Welcome to the last part of our tutorial series! In this tutorial, we are going to deploy our Django application to a production server. We are also going to configure an Email service and HTTPS certificates for our servers. At first, I thought about given an example using a Virtual Private Server (VPS), which is more generic and then using one Platform as a Service such as Heroku. But it was too much detail, so I ended up creating this tutorial focused on VPSs. Our project is live! If you want to check online before you go through the text, this is the application we are going to deploy: www.djangoboards.com. Version Control Version control is an extremely important topic in software development. Especially when working with teams and maintaining production code at the same time, several features are being developed in parallel. No matter if it’s a one developer project or a multiple developers project, every project should use version control. There are several options of version control systems out there. Perhaps because of the popularity of GitHub, Git become the de facto standard in version control. So if you are not familiar version control, Git is a good … -
PGDay.IT 2017
PGDay.IT is the Italian event dedicated to PostgreSQL, one of the most successful open-source projects. -
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) -
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 … -
Implement search with Django-haystack and Elasticsearch Part-1
Haystack works as a search plugin for Django. You can use different backends Elastic-search, Whose, Sorl, Xapian to search objects. All backends work with the same code. In this post, I am using elastic search as backend. Installation: pip install django-haystack Configuration: add haystack to installed apps INSTALLED_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', #add haystack here 'haystack', 'books' ] Settings: Add back-end settings for the haystack. HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack_books', }, } Above settings for elastic search. Add signal processor for the haystack. This signal will update objects in … -
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... -
Understanding Django Permissions And Groups
Permissions: Actually permissions are of 2 types: 1.Model level permissions 2.object level permissions If you want to give permissions on all cars, then Model-level is appropriate, but if you Django to give permissions on a per-car basis you want Object-level. You may need both, and this isn't a problem as we'll see. For Model permissions, Django will create permissions in the form 'appname.permissionname_modelname' for each model. If you have an app called 'drivers' with the Car model then one permission would be 'drivers.delete_car'. The permissions that Django automatically creates will be create, change, and delete.Read permission is not included in CRUD operation.Django decided to change CRUD's 'update' to 'change' for some reason. You can use the metaclass to add more permissions to a model.: class Book( models.Model ): # model stuff here class Meta: permissions = ( ( "read_book", "Can read book" ), ) Permissions is a set of tuples, where the tuple items are the permission as described above and a description of that permission. Finally, to check permissions, you can use has_perm: obj.has_perm( 'drivers.read_car' ) Where obj … -
Overriding Django Model behaviour with Proxy Model
The main Usage of a proxy model is to override the main functionality of existing Model. It is a type of model inheritance without creating a new table in Database. It always query on original model with overridden methods or managers. You can query, delete, edit, create etc on Proxy model but the effects will be on the original model. You can define models as a proxy just by adding proxy = True in Meta class of model. # Original Model class Employee(models.Model): EmployeeType = ( ("D", "Developer"), ("M", "Manager"), ) name = models.CharField(max_length=55) type = models.CharField(choices=EmployeeType, max_length=1, default='D') def __str__(self): return self.name # Model manager to use in Proxy model class ManagerEmpManager(models.Manager): def get_queryset(self): return super(ManagerEmpManager, self).get_queryset().filter( type='M') def create(self, **kwargs): kwargs.update({'type': 'M'}) return super(ManagerEmpManager, self).create(**kwargs) # Proxy Model class ManagerEmployee(Employee): objects = ManagerEmpManager() class Meta: proxy = True In ManagerEmployee I have overridden create method to set type … -
how to pass extra context data to serializers in django-rest-framework ?
Serializers are used to validate the data in Django rest framework. Generally, serializers provide basic validations based on the type of field. Model serializers use model validations(primary key, foreign key, unique, etc). We not only use these basic validations but also custom validations to some of the fields. For writing custom validations we may require some extra data in validation methods of serializers. Django Rest Framework Serializer takes the following parameters while creating the serializer object. read_only, write_only, required, default, initial, source, label, help_text, style, error_messages, allow_empty, instance, data, partial, context, allow_null Django serializers designed in such a way that makes an application more powerful and simplified the development process. To pass extra context data to the serializer we use "context" parameter. "context" parameter takes the data in the form of a dictionary. we access the context data inside serializer with statement "self.context" Let's take an example to understand it more clearly. Case: Send an email to any user with given content but, do not send email to the specific list of emails. For this case, we need to validate the email and raise an error if it is in excluded emails list. To do this we need to have excluded emails list … -
Upgrade All Pip & Python Packages & Store an Archive
This guide is still being deve... -
Understanding Routers in Django-Rest-Framework
We can use function-based views(FBV) and generic views(class-based views[CBV]) to develop rest API by using the Django-REST-Framework. It's a good approach to use FBV or CBV with defined URL configurations. Mapping views with the URL's is a good idea but, probably not the best. We can better organize this by using Routers and ViewSets. Advantages using ViewSets and Routers over traditional views We can avoid configuring the URL's with views. Routers generate automatic URL patterns and maps every URL to its respective method based on a type of the request. It deals with a little abstraction but, it can speed up the development process. We can also speed up the debugging process as well with a little practice. Router generates standardized url patterns. We can expect consistent behaviour from viewsets and routers We can avoid repetitive code in views. For example, in traditional views we need to have two api views for detail and list. But, we can achive it with a single ViewSet class. If we develop a large api and if we don't use viewset and routers then it will result in more views and urls. It will definitely affect our application(api) maintainablity and development time. Lets see … -
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!