Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Command Line Tricks for Ridiculously Fast Django Development
The command line is one of the most important tool in your arsenal. Knowing it well and be fast with it will seriously boost your performance and effectiveness. One side of that is knowing the commands well, the other side is aliases and custom variables. We will focus on the aliases today with the most important shortcuts. An alias is giving another name to command, possibly a much shorter one. For example you want a faster way to invoke Python interpreter. Instead of “python3” you could just type “p”. The command would go this way: alias p=python3 This setting will cease to exists when you exit the terminal. You can make it permanent if you set them in the .bashrc file in your home directory. Open up ~/.bashrc with your editor. I use nano: nano ~/.bashrc Head to the bottom of the file and copy the following: *** ~/.bashrc *** … #my custom aliases alias v=”source ../virtualenv/bin/activate” alias dea=”deactivate” alias r=”python3 manage.py runserver” alias te=”python3 manage.py test” alias c=”clear” alias mdkir=”mkdir” alias ..=”cd ..” alias ….=”cd ../..” alias …...=”cd ../../..” #my custom variables tut=”~/Tutorial/DjangoTutorial/source” // Replace it where your working directory is If you haven't followed along with the tutorial … -
Command Line Tricks for Ridiculously Fast Django Development
The command line is one of the most important tool in your arsenal. Knowing it well and be fast with it will seriously boost your performance and effectiveness. One side of that is knowing the commands well, the other side is aliases and custom variables. We will focus on the aliases today with the most important shortcuts. An alias is giving another name to command, possibly a much shorter one. For example you want a faster way to invoke Python interpreter. Instead of “python3” you could just type “p”. The command would go this way: alias p=python3 This setting will cease to exists when you exit the terminal. You can make it permanent if you set them in the .bashrc file in your home directory. Open up ~/.bashrc with your editor. I use nano: nano ~/.bashrc Head to the bottom of the file and copy the following: *** ~/.bashrc *** … #my custom aliases alias v=”source ../virtualenv/bin/activate” alias dea=”deactivate” alias r=”python3 manage.py runserver” alias te=”python3 manage.py test” alias c=”clear” alias mdkir=”mkdir” alias ..=”cd ..” alias ….=”cd ../..” alias …...=”cd ../../..” #my custom variables tut=”~/Tutorial/DjangoTutorial/source” // Replace it where your working directory is If you haven't followed along with the tutorial … -
Django Tutorial Setup
This article is an appendix to the other tutorial exercises on the site. Follow these steps to clone my repository from github and make the tutorial setup on your computer. Replace branch “exerciseX” with your current exercise branch. mkdir -p DjangoTutorial/{static,virtualenv,source,database,media} virtualenv --python=python3 DjangoTutorial/virtualenv/ git clone https://github.com/fozodavid/DjangoTutorial.git --branch exerciseX --single-branch DjangoTutorial/source cd DjangoTutorial/source touch MyTutorial/local_settings.py ***MyTutorial/local_settings.py*** import os from MyTutorial.settings import BASE_DIR SECRET_KEY = 'rf@7y-$2a41o+4&z$ki0&=z)(ao=@+$fseu1f3*f=25b6xtnx$' DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR,'..','database','db.sqlite3'), } } *** end of MyTutorial/local_settings.py *** git branch -m exerciseX master source ../virtualenv/bin/activate pip install django==1.10 deactivate You are ready to start development. -
JSON Web Tokens in django application- part four
When I started this series I have got one comment from my co-worker that instead of authentication JWT can be used to sign one time links. After reading through the documentation I found that can be a great idea so I decided to write a blog post about it. Table of Contents: Use case JSON Web Tokens in urls Other blog posts in this series Use case Nowadays when a user creates an account he or she has to confirm identity. It is done by sending an email with the link to confirm and activate an account. As this link has to expire and be safe this is a good use case for using JSON Web Tokens. Such tokens can be generated for every user and set to expire for example after two hours. How can it be done in Django? Let's jump into the code. JSON Web Tokens in urls First I change the previous code from series and made special django app just for users. But the first user has to register - that's why I made new endpoint in urls.py: from users.views import UserViewSet, CreateUserView, urlpatterns = [ # rest of url patterns url('^api-register/$', CreateUserView.as_view()), ] CreateUserView … -
JSON Web Tokens in django application- part four
When I started this series I have got one comment from my co-worker that instead of authentication JWT can be used to sign one time links. After reading through the documentation I found that can be a great idea so I decided to write a blog post about it. Table … -
JSON Web Token (JWT) Authentication in a Django/AngularJS web app
No matter if you are an experienced developer or if you are starting your first app, there is a task that we all face someday in our life as developers: user’s authentication. Nowadays, there are several kinds of authentication techniques available, and many of them could fit your needs. Nevermind, this post is not about authentication mechanisms, it is about how to implement JSON Web Token Authentication in an application with a Django-based backend, using a REST API to offer resources for an AngularJS frontend app (which fits very well in the Octobot’s technologies stack, and maybe in yours) First of all, why JWT? Well, because it is a compact and self-contained way for securely transmitting information between parties as a JSON object. Compact is good (we all know that), but self-contained? The JWT payload contains all the required information about the user, avoiding the need to query the database more than once. This makes JWT lightweight, scalable and easy to use. Once a user was successfully logged in to your application using a username and password, he/she obtains a JWT which should be sent in every further request to the backend as an Authorization Header, and this token will … -
Common web site security vulnerabilities
I recently decided I wanted to understand better what Cross-Site Scripting and Cross-Site Request Forgery were, and how they compared to that classic vulnerability, SQL Injection. -
Django's models, views and templates
Django loosely follows the MVC design pattern. That stands for Model-View-Controller. Model is the database handling layer defined in models.py, View is the display layer (html files), that is defined in the “templates” directory and also views.py doing this. The Controller is responsible for the user's input, surprisingly that work is also done in the views.py file. You will see these parts in action all working together. In todays tutorial we will display an article on our website. Let's dive in! If you haven't follow earlier tutorials, click here and clone branch exercise2. As with the previous tutorial, we will follow git and TDD best practices. So let's create a new branch for the new feature we will implement. Let's call that article branch: git checkout -b article git branch You should see two branches and “article” selected: * article master Let's activate virtualenv. source ../virtualevn/bin/activate Let's create our homepage. Before anything else, the principle of TDD require us to write so some tests. We will test if our root domain (e.g.: example.com) will return our index.html template. Our bet if it starts with <!doctype html> and there is “Hello World” in it, then it's a good enough test to … -
Django Under the Hood 2016
This was the third edition of the Django: Under The Hood (DUTH) conference. Two days of awesome talks and two days of sprints. The conference was organised by members of the Django community, including several members of the Django core team, and in association with the Dutch Django Association. The conference was great! It was my first time in a DUTH conference and also my first time in Amsterdam, so it was quite an experience for me! I’m writing this post to share a little bit of what happened there. About the Conference Picture by Bartek Pawlik: https://500px.com/photo/181370473/group-photo-at-django-under-the-hood-2016-by-django-under-the-hood Over 300 Djangonauts. Stellar organization. Nine great talks. Two days of sprints. Awesome venue. Very healthy and friendly community. You could feel the excitement and enthusiasm of everyone participating in the conference. This was quite a surprise for me! Because the parameter of comparison I had was previous academic conferences I’ve attended – and they are far from being that fun :-) In the first day we had three talks, starting by Andrew Godwin presenting the underlyings of Channels and discussing about the Django specific implementations. Ana Balica talked about testing in Django, she presented how the testing framework have evolved since … -
Git Workflow with Django
Git is the most popular version control software right now, and will be for a long time. The git workflow is branch based. What that means, is that you can experimenting with ideas, by open up a new branch and you can easily discard the changes, if you aren't satisfied with it. On the other hand, if your branch proves to be successful you can “merge” it into the “master”. This structure lets you control the versions of your program to a great extent. Combine this methodology with unit testing and you can make no mistake. Let's dive in! If you haven't done the earlier tutorial I have “How to start a Django application”, you can clone my repository from github: mkdir -p DjangoTutorial/{static,virtualenv,source,database,media} virtualenv --python=python3 DjangoTutorial/virtualenv/ git clone https://github.com/fozodavid/DjangoTutorial.git --branch exercise1 --single-branch DjangoTutorial/source cd DjangoTutorial/source touch MyTutorial/local_settings.py ***MyTutorial/local_settings.py*** import os from MyTutorial.settings import BASE_DIR SECRET_KEY = 'rf@7y-$2a41o+4&z$ki0&=z)(ao=@+$fseu1f3*f=25b6xtnx$' DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR,'..','database','db.sqlite3'), } } *** end of MyTutorial/local_settings.py *** git branch -m exercise1 master source ../virtualenv/bin/activate pip install -r requirements.txt If you come from earlier tutorial, just cd into the source directory and put into the terminal: git checkout … -
Django Under The Hood 2016 recap
From the beginning I really wanted to contribute to Django. I asked a friend of mine- "Do you know where I can start contributing?" She answers- "Go to Django Under The Hood". So I went. This is my small recap of this very event. Table of Contents: Day one Day two Day three & four Conclusion Day one After wandering a little bit around the city I finally got to the venue and the talks started- the first one was Channels by Andrew Godwin. Until then I had heard about this topic but I hadn't really go into details for what it is useful for. Andrew presented a very thought-through understanding of what channels really are and for what they can be used. But I would like to see them in production to see how this gonna work. As a guy who hadn't heard about this topic before I liked it very much. Right after that was a talk about testing by Ana Balica. She started by introducing about how testing in django evolved which I really liked. Then there was an introduction what is happening when you execute test suite via django. And what is happening in various testcases … -
Django Under The Hood 2016 recap
From the beginning I really wanted to contribute to Django. I asked a friend of mine- "Do you know where I can start contributing?" She answers- "Go to Django Under The Hood". So I went. This is my small recap of this very event. Table of Contents: Day one Day … -
Django under the hood: funding open source, the hard way - Nadia Eghbal
(One of my summaries of a talk at the 2016 django under the hood conference). You don't do open source for the money. Django's projected revenue (the DSF) is 200.000. Instagram's is 3.200.000.000.... If you want to have funding for open source, money itself is not the problem. There is enough money. The real problem is access to money. As a home-owner, you can get a loan from the bank. As a start-up you can try and find investors. But as open source, there's no clear way. You could do things with tipping, bug bounties and so, but that just tries to grab a bit of ready cash, it doesn't provide regular funding. Many major open source projects were started by employees. Including Django! It is an environment where you can do some experiments and if they go wrong, you still have your regular job. A further problem: maintenance of existing projects instead of starting something new. Maintenance is hard. Very good that the django software foundation managed to hire someone (Tim) to basically work on django maintenance. The last releases have been the first ones that happened on time :-) We need to figure out four things: Who needs … -
Django under the hood: validation - Loïc Bistuer
(One of my summaries of a talk at the 2016 django under the hood conference). Loïc has mostly worked on forms and the ORM. The main concerns with validation are: Enforcement. User experience Performance Convenience Some items go well together. Enforcement and user experience like each other. You don't want wrong data. And you want good feedback. Validation helps with that. But "user experience" and "performance" are harder to combine. Checks do cost time. Similarly "user experience" and "developer convenience". Why do you have to check anything on the backend when you already checked it on the front end? Extra work. Where to validate data? You can do it in the front end: javascript, html5/browser or in native code like phone apps. The nice thing is that it is fast and provides direct feedback. The drawback is that you have to do the same thing on the backend again, as you cannot trust anything coming in from the front end. You can also use forms and the django rest framework serializer. Designed for the task, but it is easy to circumvent. Similarly django views. You could do validation directly on the model. Only problem is that it isn't run by … -
Django under the hood: keynote about mental health in tech - Jennifer Akullian
(One of my summaries of a talk at the 2016 django under the hood conference). The trust equation: Trust = (credibility + reliability + intimacy) / self-orientation. If you want to build trust with someone, keep this equation in mind. She asked for a show of hands: "how many people have glasses or contact lenses?" Afterwards she asked "how many people have been told to just try harder instead using glasses?" Laughter, no hands went up. "Well, I have a mental illness and have been told to try harder. Just focus on happy things, just try to be more happy, etc..." She has bipolar disorder. Found in about 2.6% in the population. It is genetic. It takes on average 7 years for someone to be accurately diagnosed, which is a strangely long time. She showed a diagram of three neurotransmitters (dopamine, norepinephrine, serotin) that don't chemically function well for her and listed some of the medications she takes. "Would it feel as uncomfortable if I would talk about medicines for a body illness? No. Does it feel uncomfortable to talk about medicines for a mental illness? Yes." The reasson: there is a stigma on it. Everybody knows the problem, but … -
Django under the hood: modern javascript - Idan Gazit
(One of my summaries of a talk at the 2016 django under the hood conference). There's some negative sentiment around Javascript. It might be hard. You might be scared of it. It is much less elegant than python. Etc. With "modern javascript" he means "civilized javascript". So how to work with javascript without missing python terribly. There are a lot of reasons why javascript might feel scary. Callback hell. Weird prototyping instead of regular classes. Less syntactic sugar. But.... javascript is the only runtime that is shipped with every browser! How did we get here? Originally, javascript saw limited use to put snow on your screen during christmas time and some form validation. Then came google with a super-fast javascript engine, V8. Node (=server side javascript) is basically the V8 engine with some libraries. So you have the browser world and the node world. Packaging for the browser is by hand or with bower and so. Packaging for node is done with "npm". For a long time, "ecmascript 5" was the main javascript. A bit like python 2. Everybody supported it. in 2015 there finally came a new, improved version: "ES6", "ecmascript 6". They've now decided to bring out a … -
Django under the hood: custom database backends - Michael Manfre
(One of my summaries of a talk at the 2016 django under the hood conference). Tip: watch django in depth by James Bennett. The database backend is right there at the bottom of the lowest level. What does the database backend do? It sits between the Django ORM and the actual database driver. There's a PEP249, the DB-API 2.0 specification for python code to talk to the actual database driver. Django abstracts away many of the differences between databases. But not all databases are created equal, so sometimes supporting what django expects is hard. Michael maintains the microsoft sql backend and showed some of the differences. If you need a custom database backend, you could subclass an existing django database backend. There's a read-only postgres db backend that has only a few lines of code. But if you create one from scratch, you need to implement about 8 classes. The DatabaseWrapper talks to the PEP249 python database library. Important: the "vendor" string to help django do specific things when it uses your database. There are other attributes that tell django how to map simple queries to actual SQL. iexact, less than, stuff like that. CursorWrapper. This one wraps the database … -
Django under the hood: django at instagram - Carl Meyer
(One of my summaries of a talk at the 2016 django under the hood conference). Instagram is huge. He mentioned a number of fun facts with lots of zeros in them. Oh, and cat photo's. They have tens of thousands django instances. Instagram started in 2010. According to one of the founders, django was super easy set-up. There is one obvious way of doing things. There's a test framework build-in. A few months later, october 2010, they had 1 million users. In June 2011, instagram had 5 million users. All in the database. With database routers they could partition it over multiple servers. The django ORM was managing those 5 million users in the database just fine. But slowly the number of likes was getting too much. It needed custom sharding. They used postgres schemas, which is more like a "logical shard". They could then map those logical shards at will unto actual physical servers. In the end, they started a custom ORM to better handle the huge amount of sharding that they needed. The likes were moved over first, two years later the user data moved. The Django ORM is still used in places, but the huge data is … -
How to start developing a Django project?
Django is the most popular Python web framework to date. The tagline “For perfectionist with deadlines” perfectly sums up what you can expect if you start using it. You have control over every aspect of your application, but it require some serious commitment to wield that power. When in doubt check out the excellent documentation, which will definitely solve most of your challenges. This blog post is about how to start developing a Django Project on your computer. I am assuming you are using Linux operating system, specifically Ubuntu. Also, I had absolute beginners in mind. This is a technical tutorial about what exact commands you need to put in, to get up and running. That said, let's start: Basic Directory Structure First, create a directory you want your project in: mkdir -p DjangoTutorial/{media,static,virtualenv,database} (don't leave spaces in the last part) This command creates the whole directory tree for you: DjangoTutorial/ database/ media/ static/ virtualenv/ Navigate into DjangoTutorial, then initiate virtualenv with the following command: cd DjangoTutorial virtualenv –python=python3 ./virtualenv Virtual Environment will make sure, that you will have consistent environments when you deploy your application to different servers. You will install plugins and packages, and you will replicate those … -
Optimization of QuerySet.get() with or without select_related
If you know you're going to look up a related Django ORM object from another one, Django automatically takes care of that for you. To illustrate, imaging a mapping that looks like this: class Artist(models.Models): name = models.CharField(max_length=200) ... class Song(models.Models): artist = models.ForeignKey(Artist) ... And with that in mind, suppose you do this: >>> Song.objects.get(id=1234567).artist.name 'Frank Zappa' Internally, what Django does is that it looks the Song object first, then it does a look up automatically on the Artist. In PostgreSQL it looks something like this: SELECT "main_song"."id", "main_song"."artist_id", ... FROM "main_song" WHERE "main_song"."id" = 1234567 SELECT "main_artist"."id", "main_artist"."name", ... FROM "main_artist" WHERE "main_artist"."id" = 111 Pretty clear. Right. Now if you know you're going to need to look up that related field you can ask Django to make a join before the lookup even happens. It looks like this: >>> Song.objects.select_related('artist').get(id=1234567).artist.name 'Frank Zappa' And the SQL needed looks like this: SELECT "main_song"."id", ... , "main_artist"."name", ... FROM "main_song" INNER JOIN "main_artist" ON ("main_song"."artist_id" = "main_artist"."id") WHERE "main_song"."id" = 1234567 The question is; which is fastest? Well, there's only one way to find out and that is to measure with some relatistic data. Here's the benchmarking code: def f1(id): … -
Managing multiple Python projects: Virtual environments
Even Python learning materials that get into very advanced language features rarely mention some practical things that would be very helpful to know as soon as you start working on more serious projects, like: -
Django under the hood: Channels - Andrew Godwin
(One of my summaries of a talk at the 2016 django under the hood conference). Django channels was started by Andrew Godwin, best known for his work on South and django migrations. Channels might seem like magic, but it is not. He'll start by describing the problem and then the actual django channels work. The problem: the web is changing A lot of the web is becoming async. Web sockets and so. But it is not only websockets: long-polling, webrtc, MQTT, server-sent events. This doesn't match django's regular webpage behaviour very well. Python is synchronous. Only the latest python 3 releases have async build-in. But even then, Django is still synchronous at the core. Synchronous code is easier to write. Async is much harder. Only do it if you really have to. Synchronous code is much easier to reason about. Single-process async is not good enough, so you'll have multiple processes, threads and perhaps even machines. You'll need a proven design pattern that isn't too hard to reason about. This is no place to do something weird and new. Multiple people must be able to maintain it. And if you use it, you'll need many people who are able to … -
DSA ssh keys also deprecated in OSX Sierra
I've been using an ssh key for a long time. Back in the days when RSA keys were mostly commercial/proprietary and when DSA keys where the recommended method. When ubuntu 16.04 came out, I suddenly couldn't use my key anymore as ubuntu (or perhaps rather its updated ssh server) didn't accept DSA keys anymore. They're apparently not save enough anymore. I worked around it by adding a setting on the server, telling it to accept my DSA key. When the latest Apple OS update (Sierra) came out, I suddenly couldn't log in anywhere. Also git pull to github (I'm using ssh) stopped working. I found the cause by passing -vvvv to ssh: debug1: Next authentication method: publickey debug1: Trying private key: /Users/reinout/.ssh/id_rsa debug3: no such identity: /Users/reinout/.ssh/id_rsa: No such file or directory debug1: Trying private key: /Users/reinout/.ssh/id_ecdsa debug3: no such identity: /Users/reinout/.ssh/id_ecdsa: No such file or directory debug1: Trying private key: /Users/reinout/.ssh/id_ed25519 debug3: no such identity: /Users/reinout/.ssh/id_ed25519: No such file or directory debug2: we did not send a packet, disable method debug3: authmethod_lookup password debug3: remaining preferred: ,password debug3: authmethod_is_enabled password debug1: Next authentication method: password Oh.... Sierra's ssh client also doens't like DSA anymore. Ok... time to create a … -
Django under the hood: testing - Ana Balica
(One of my summaries of a talk at the 2016 django under the hood conference). A quick history of django's testing framework. Ticket #2333 got added to django's bug tracker before 1.0 was out: we want an integrated test framework ("Rails has it too"). A while later there was a test runner that looked at tests.py and models.py. models.py? Yes, as at that time doctests were still very popular and models were commonly tested with doctests. The rest was for the normal tests in tests.py. Django 1.1 added a build-in testclient for basic GET/PUT. Also TransactionTestCase was added: this one rolled back database transactions at the end of the tests. Better performance. 1.2 added a new class-based test runner. You could now also terminate the entire test run upon the first error ("failfast"). 1.3 splits the old test client into an actual client and a RequestFactory. Well, the client is a subclass of RequestFactory, something Ana doesn't like and would like to see refactored during the sprints. Doctests turned out not to be an ideal combination of tests and documentation. Testing was harder and the documentation not clear. So doctests were discouraged. In 1.4, more TestCases were added. SimpleTestcase for … -
Django under the hood: debugging performance - Aymeric Augustin
(One of my summaries of a talk at the 2016 django under the hood conference). Performance? Partially it is a question of perception. Up to 0.1s is "reacting instantaneously". Up to 1s: "not interrupting the user's flow of thought". Up to 10 seconds is slow, but the user might keep waiting. More than 10 seconds and they're off to check facebook. To optimize something, we have to measure it. For instance page load time. You could use your browser's development tools to see how quick a page loads. But you're measuring that on your fast development laptop. In chrome, you can make your internet connection worse and simulate 3G speed, for instance. Google analytics site speed can be used, it measures it in 1% of the cases a user looks at your page. Performance timeline Let's look at what happens for one single request. DNS lookup. This can take a surprising amount of time. Establish a TCP connection. Finally send over the request to the webserver. You receive the first byte of the response. After a while the last byte comes in. Page processing in the browser itself. Rendering the page and so. onLoad javascript and so. On average, the …