Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
How to Add User Profile To Django Admin
There are several ways to extend the the default Django User model. Perhaps one of the most common way (and also less intrusive) is to extend the User model using a one-to-one link. This strategy is also known as User Profile. One of the challenges of this particular strategy, if you are using Django Admin, is how to display the profile data in the User edit page. And that’s what this tutorial is about. Background I’ve published a while ago an article about How to Extend Django User Model, describing in great detail all the different strategies. If you are still not familiar with it, I strongly suggest that you have a look in this article. This tutorial is about the User Profile strategy. So, consider we have an app named core with the following model definition: models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): STUDENT = 1 TEACHER = 2 SUPERVISOR = 3 ROLE_CHOICES = ( (STUDENT, 'Student'), (TEACHER, 'Teacher'), (SUPERVISOR, 'Supervisor'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return … -
Django Multiple Files Upload Using Ajax
In this tutorial I will guide you through the steps to implement an AJAX multiple file upload with Django using jQuery. For this tutorial we will be using a specific plug-in called jQuery File Upload, which takes care of the server communication using AJAX and also the compatibility with different browsers. The plug-in is great, but it have so many features that sometimes it can become challenging for some to get started. You will notice that some of the examples are a little bit redundant, repeating code and so on. That’s on purpose, so to avoid code abstraction and the examples become more clear. In the end of this post you will also find the link to download all the code used in this tutorial. Basic Configuration Before you move forward, if you are not familiar at all with file upload with Django, it is a good a idea to check this post I published while ago: How to Upload Files With Django. It will give you an overview of the basics and some caveats. To work with file upload you will need to set the MEDIA_URL and MEDIA_ROOT. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And to test … -
Django Under the Hood 2016 Highlights
Videos from Django Under the Hood 2016 are up - check ‘em out! As usual, the conference was amazing and the content was fantastic. I really enjoyed all the talks, and they’re all worth your time to talk. Three in particular stood out to me as exceptional highlights: Ana’s talk on Testing in Django is the single best talk on effective testing of Django apps I’ve ever seen. I really like her technique of explaining Django’s testing APIs by looking at how they changed over time: it does a great job of explaining what problems particular APIs solve, and why you’d use them. -
Django Grils- Kraków #3
As I said many times on this blog I really like teaching others so I can improve myself. That's why when I heard about Django Girls Kraków I didn't hesitate and I joined this event as a coach. This is short recap from Django Girls Kraków #3. Table of Contents: Installation party Workshop day Conclusion Installation party The main event was held on Saturday but the day before there was a small installation party when for two hours girls were installing necessary tools for workshops such as python, django virtualenv and git. When it comes to my team there were 3 girls on it: Joanna, Olga and Magda. Before the Django Girls organizators came up with a wonderful idea that to get to know everyone in the team a little bit better, every person has to write a few sentences about themselves. Thanks to that there were already conversation starters. The installation went well without any major problems (considered that girls used Windows). After the installation party there was a pleasant surprise - dinner for coaches to thank for their work. Super cool! Workshop day Workshops started early - at 9 am. Girls started working on django girls tutorial. I … -
Django Grils- Kraków #3
As I said many times on this blog I really like teaching others so I can improve myself. That's why when I heard about Django Girls Kraków I didn't hesitate and I joined this event as a coach. This is short recap from Django Girls Kraków #3. Table of Contents … -
A Primer to Django Forms
If you want some interactivity with your users, it all starts with forms. Luckily Django provides some out of the box straightforward solution for us. For this tutorial we are going to do a basic website for surveying a person's age, eye color, name and whether he wants to subscribe or not. If you haven't followed along, you can initiate the tutorial repository if you download it from my Github account. Choose branch exercise3. Further instructions here. So first of all, we have an idea that, we should implement a new feature. For that, we need to create a new “feature branch”. So we can freely experiment, and only merge it when the feature is properly implemented. This new feature will be a form, so let's do this: git checkout -b form git branch You can see that we have, two branches now: * form master As good TDD development practice. Start by writing a test first. New feature deserves it's own test class. Also I know that I will need a new function from main.views. You will see that later. ***main/tests.py*** ... from main.views import home, form … class FormTest(TestCase): def test_form_renders_on_page_properly(self): request = HttpRequest() response = form(request) for … -
RapidCon 2016: RapidPro Developer's Recap
Developer Erin Mullaney was just in Amsterdam for RapidCon, a UNICEF-hosted event for developers using RapidPro, an SMS tool built on Django. The teams that have worked on RapidPro and its predecessor RapidSMS have gotten to know each other virtually over the years. This marks the second time they’ve all come from across the globe to share learnings on RapidPro and to discuss its future. RapidPro has the potential to transform how field officers build surveys, collect data, and notify populations. It allows users with no technical background to quickly build surveys and message workflows. With over 100% cell phone saturation in many developing regions, SMS presents a cheap, fast means of reaching many quickly. Erin worked closely with UNICEF Uganda in the development of a data analytics and reporting tool called TracPro for RapidPro. The organizers invited her to speak about the tool with other RapidPro users. How was the conference? Erin: The conference was amazing and I was ecstatic to go. Meeting the folks who work at UNICEF for the first time was exciting because we normally only speak via audio over Skype. It was nice to see them in person. We had an evening event, so it … -
How does the Django Cross-site request forgery protection work?
Dan Poirier wrote an article on the Cactus Group blog about common web site security vulnerabilities. In it he talked about the CSRF protection in Django. Although he is right about a CSRF token having to be part of the POST request, this is not the entire story. It is not my intention to claim that mister Poirier does not know how the CSRF protection in Django works. I only want to present a more complete version. First things first, for those of you that have not read the Dan Poiriers article, here’s a short summary of the CSRF related parts. Cross-site request forgery (CSRF or XSRF) is a type of attack where a malicious site is trying to make your browser send requests to another site in an attempt to leverage the permissions of the user—you. (For more information and examples, check the original article or the OWASP page on CSRF.) Besides making sure that GET requests do not change data the article talks about the CSRF protection provided by Django. Specifically it states the following (emphasis mine): Django’s protection is to always include a user-specific, unguessable string as part of such requests, and reject any such request that doesn’t include it. This … -
How does the Django Cross-site request forgery protection work?
Dan Poirier wrote an article on the Caktus Group blog about common web site security vulnerabilities. In it he talked about the CSRF protection in Django. Although he is right about a CSRF token having to be part of the POST request, this is not the entire story. It is not my intention to claim that mister Poirier does not know how the CSRF protection in Django works. I only want to present a more complete version. First things first, for those of you that have not read the Dan Poirier’s article, here’s a short summary of the CSRF related parts. Cross-site request forgery (CSRF or XSRF) is a type of attack where a malicious site is trying to make your browser send requests to another site in an attempt to leverage the permissions of the user—you. (For more information and examples, check the original article or the OWASP page on CSRF.) Besides making sure that GET requests do not change data the article talks about the CSRF protection provided by Django. Specifically it states the following (emphasis mine): Django’s protection is to always include a user-specific, unguessable string as part of such requests, and reject any such request that … -
How to Implement CRUD Using Ajax and Json
Using Ajax to create asynchronous request to manipulate Django models is a very common use case. It can be used to provide an inline edit in a table, or create a new model instance without going back and forth in the website. It also bring some challanges, such as keeping the state of the objects consistent. In case you are not familiar with the term CRUD, it stand for Create Read Update Delete. Those are the basic operations we perform in the application entities. For the most part the Django Admin is all about CRUD. Table of Contents Basic Configuration Working Example Listing Books Create Book Edit Book Delete Book Conclusions Basic Configuration For this tutorial we will be using jQuery to implement the Ajax requests. Feel free to use any other JavaScript framework (or to implement it using bare JavaScript). The concepts should remain the same. Grab a copy of jQuery, either download it or refer to one of the many CDN options. jquery.com/download/ I usually like to have a local copy, because sometimes I have to work offline. Place the jQuery in the bottom of your base template: base.html {% load static %}<!DOCTYPE html> <html lang="en"> <head> <meta … -
Gitのチートシート
GitのGUIはwww.gitkraken.comがおすすめです。 新しいブランチの作成 git branch new_feature ブランチをチェックアウト git checkout new_feature 新しいブランチを作成し、チェックアウトをする git checkout -b new_feature レポジトリのステータスチェック git status すべての変更されたファイルをステージングエリアに追加 git add . 特定のフォルダ、ファイルをステージングエリアに追加 git add test.py ステージングされたファイルをコミット git commit -m "commit message" コミットヒストリーを確認 git log masterブランチに新しいコミットをプッシュする git push origin master Gitのチートシートはw3b.jpで公開された投稿です。 -
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. I also looked into some ways that sites protect against those attacks. Vulnerabilities SQL Injection SQL Injection is a classic vulnerability. It probably dates back almost to punch cards. Suppose a program uses data from a user in a database query. For example, the company web site lets users enter a name of an employee, free-form, and the site will search for that employee and display their contact information. A naive site might build a SQL query as a string using code like this, including whatever the user entered as NAME: "SELECT * FROM employees WHERE name LIKE '" + NAME + "'" If NAME is "John Doe", then we get: SELECT * FROM employees WHERE name LIKE 'John Doe' which is fine. But suppose someone types this into the NAME field: John Doe'; DROP TABLE EMPLOYEES; then the site will end up building this query: SELECT * FROM employees WHERE name LIKE 'John Doe'; DROP TABLE EMPLOYEES;' which might delete the whole employee directory. It could instead do something less obvious but even … -
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 … -
Securing Django with multi factor authentication using Django-MFA
What is MFA? Multifactor authentication (MFA) is a security system that requires more than one method of authentication to verify the user’s identity for a login or other transaction. Why go for MFA? One of the major problems with traditional user ID and password login is the need to maintain a password database. Whether encrypted or not, if the database is captured it provides the hacker with a source to verify his guesses at speeds limited only by his hardware resources. Given enough time, a captured password database will fall. To avoid this break we do prefer multifactor authentication. Multifactor Authentication Technologies: There are multiple ways we could get the MFA like using hardware devices that the user carries to authorize access to a network service. Software-based security token applications that generate a single-use login PIN. Soft tokens are often used for multifactor mobile authentication, in which the device itself – such as a smartphone – provides the possession factor or SMS messages and phone calls sent to a user as an out-of-band method, smartphone OTP apps. In the current blog post, we see how to implement MFA in Django. How can we implement MFA in Django: We do have … -
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 …