Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Tips & Tricks #12 - Automatically Set CSRF Token in Postman
Introduction Django has inbuilt CSRF protection mechanism for requests via unsafe methods to prevent Cross Site Request Forgeries. When CSRF protection is enabled on AJAX POST methods, X-CSRFToken header should be sent in the request. Postman is one of the widely used tool for testing APIs. In this article, we will see how to set csrf token and update it automatically in Postman. CSRF Token In Postman Django sets csrftoken cookie on login. After logging in, we can see the csrf token from cookies in the Postman. We can grab this token and set it in headers manually. But this token has to be manually changed when it expires. This process becomes tedious to do it on an expiration basis. Instead, we can use Postman scripting feature to extract token from cookie and set it to an environment variable. In Test section of postman, add these lines. var xsrfCookie = postman.getResponseCookie("csrftoken"); postman.setEnvironmentVariable('csrftoken', xsrfCookie.value); This extracts csrf token and sets it to an evironment variable called csrftoken in the current environment. Now in our requests, we can use this variable to set the header. When the token expires, we just need to login again and csrf token gets updated automatically. Conclusion … -
How 5G Network Development Will Go Global In 2019
The next generation of mobile internet connection is just around the corner. Carriers, manufacturers, vendors and companies are preparing for the introduction of 5G. If you don’t know what is 5G already, it is the 5th generation of mobile networking technology that promises to bring even faster and more reliable wireless connections across the globe. With testing and small market launches already in progress, we expect to see rapid adoption of the 5G network in 2019. Here are the anticipated 5G network developments coming up in the next year. The post How 5G Network Development Will Go Global In 2019 appeared first on Distillery. -
Sorry I seemed to have missed this!
Sorry I seemed to have missed this! The @next label is used for anything that doesnt have a due date, but can be worked on anytime. That way my filters have a list of things that are due that day (@waiting-for & today) as well as items I can start working on anytime (@next) -
You are right, if I mentioned @wait-for I meant @waiting-for, Ill look over the article and see if…
You are right, if I mentioned @wait-for I meant @waiting-for, Ill look over the article and see if I can fix that issue.The @next label is used for anything that doesnt have a due date, but can be worked on anytime. That way my filters have a list of things that are due that day (@waiting-for & today) as well as items I can start working on anytime (@next) -
Django ORM optimization story on selecting the least possible
This an optimization story that should not surprise anyone using the Django ORM. But I thought I'd share because I have numbers now! The origin of this came from a real requirement. For a given parent model, I'd like to extract the value of the name column of all its child models, and the turn all these name strings into 1 MD5 checksum string. Variants The first attempted looked like this: artist = Artist.objects.get(name="Bad Religion") names = [] for song in Song.objects.filter(artist=artist): names.append(song.name) return hashlib.md5("".join(names).encode("utf-8")).hexdigest() The SQL used to generate this is as follows: SELECT "main_song"."id", "main_song"."artist_id", "main_song"."name", "main_song"."text", "main_song"."language", "main_song"."key_phrases", "main_song"."popularity", "main_song"."text_length", "main_song"."metadata", "main_song"."created", "main_song"."modified", "main_song"."has_lastfm_listeners", "main_song"."has_spotify_popularity" FROM "main_song" WHERE "main_song"."artist_id" = 22729; Clearly, I don't need anything but just the name column, version 2: artist = Artist.objects.get(name="Bad Religion") names = [] for song in Song.objects.filter(artist=artist).only("name"): names.append(song.name) return hashlib.md5("".join(names).encode("utf-8")).hexdigest() Now, the SQL used is: SELECT "main_song"."id", "main_song"."name" FROM "main_song" WHERE "main_song"."artist_id" = 22729; But still, since I don't really need instances of model class Song I can use the .values() method which gives back a list of dictionaries. This is version 3: names = [] for song in Song.objects.filter(artist=a).values("name"): names.append(song["name"]) return hashlib.md5("".join(names).encode("utf-8")).hexdigest() This time Django figures it doesn't even … -
Adding custom filters to Django admin is easy!
I'm building a backend for a scraping tool that has two simple models Website and Page, where Website can have many pages. In a simplified form it looks like: class Website(models.Model): url = models.URLField(unique=True) class Page(models.Model): website = models.ForeignKey( 'Website', on_delete=models.CASCADE ... Read now -
Guide to Ansible/NGINX/uWSGI/Django, Part 2: Getting uWSGI Working with NGINX and Django
In Part 1 of this post, I described the trials, tribulations and ultimate success of running Ansible to provision a cloud server, which we do often here at Imaginary Landscape. Part 2 concludes the post by describing the process for getting uWSGI working with NGINX and Django. When I first tested the deployed website after doing the provisioning with Ansible, it failed with a not-very-descriptive "bad gateway" error. Luckily, uWSGI's own documentation provides an excellent tutorial on how to configure uWSGI, NGINX, and Django. Given the average quality of documentation one usually finds online, it's almost shocking how clear and thorough this tutorial is. It shows you step-by-step how to test each component until you get your Django app working with uWSGI and NGINX. It's great. The only downside is that because the tutorial is so thorough and because it assumes that you are setting up uWSGI, NGINX and Django from scratch (i.e., not with an Ansible script), working through it takes time. Nevertheless, when all three of those tools are in play, tracking down the cause of errors can be very difficult. Stripping the system down and checking each component in isolation, as the tutorial describes, might still be the best way forward. … -
Data Warehouse vs. Data Lake: Which Is Right for Your Enterprise App Development Effort?
So you’re building an app for your enterprise. While your primary purpose for building that app may take countless forms, that purpose is at least partly driven by the desire to collect and store “big data” that can be translated into business intelligence (BI). Why? BI allows you to translate your data into actionable information that helps you drive better business decisions. The post Data Warehouse vs. Data Lake: Which Is Right for Your Enterprise App Development Effort? appeared first on Distillery. -
Our Little Scoop
Last month we welcomed a little scoop to the family. Here is our daughter Uma. She has been eating ice cream since before she was born. She's our only child, and we love her so much. -
Our Little Scoop
Last month we welcomed a little scoop to the family. Here is our daughter Uma. She has been eating ice cream since before she was born. She's our only child, and we love her so much. -
Our Little Scoop
Last month we welcomed a little scoop to the family. Here is our daughter Uma. She has been eating ice cream since before she was born. She's our only child, and we love her so much. -
How to Export Data to XLSX Files
A while ago I wrote an article about exporting data to different spreadsheet formats. As recently I was reimplementing export to Excel for the 1st things 1st project, I noticed that the API changed a little, so it's time to blog about that again. For Excel export I am using the XLSX file format which is a zipped XML-based format for spreadsheets with formatting support. XLSX files can be opened with Microsoft Excel, Apache OpenOffice, Apple Numbers, LibreOffice, Google Drive, and a handful of other applications. For building the XLSX file I am using openpyxl library. Installing openpyxl You can install openpyxl to your virtual environment the usual way with pip: (venv) pip install openpyxl==2.6.0 Simplest Export View To create a function exporting data from a QuerySet to XLSX file, you would need to create a view that returns a response with a special content type and file content as an attachment. Plug that view to URL rules and then link it from an export button in a template. Probably the simplest view that generates XLSX file out of Django QuerySet would be this: # movies/views.pyfrom datetime import datetimefrom datetime import timedeltafrom openpyxl import Workbookfrom django.http import HttpResponsefrom .models import … -
Guide to Ansible/NGINX/uWSGI/Django, Part 1: Running the Ansible Scripts
Here at Imaginary Landscape, we are frequently tasked with spinning up new cloud servers for our clients. Once a new server is online, we usually follow up by provisioning it with useful software. To automate that process, we began using Ansible a few years ago, and have had a lot of success with it. Provisioning is complicated by nature, however, and no provisioning attempt has been completely free of difficulty. This post examines a recent provisioning and uses it to expose issues that caused pain. Some of this is undoubtedly a case of the day-to-day getting in the way of tying up loose ends, but other aspects represent more generic problems. It is in the latter category where we hope this post might hold some wider value for the reader. Ansible offers a lot of flexibility in terms of how its configuration is laid out. A very pared-down version of ours looks like this: ansible-django-stack/ ├── extra-variables.yml ├── ansible/ └── ├── inventory.ini └── roles/ │ └── django/ │ └── tasks │ └── base.yml └── playbooks/ ├── playbook-all.yml └── playbook-all.retry Now let's look at what some of those files do. STEP 1: The Inventory File Our Ansible uses an inventory.ini file to obtain the … -
Meet Distillery’s Newest Scholarship Recipient: Andrew Chatman!
Well-functioning software is vital to keeping our world moving smoothly forward. At Distillery, we do our part by building reliable, secure, thoughtfully designed software that helps our clients build business success. We also do our part by supporting the next generation of developers: students who demonstrate outstanding promise in IT, computer science, or software engineering. The post Meet Distillery’s Newest Scholarship Recipient: Andrew Chatman! appeared first on Distillery. -
Django File (and Image) Uploads Tutorial
Learn how to add user-uploaded files and images to a Django project. -
Mercurial Mirror For Django 2.1 Branch
I’m slightly late on this one, but here it is. For the record, main purposes of this mirror are: being a lightweight read-only repository to clone from for production servers hide the ugly git stuff behind a great mercurial interface The clone is at the usual location at bitbucket, from which you can browse, clone, […] -
Django Tips #8: Projects vs Apps
An explanation of Django structure and what constitutes an "app." -
An Introduction to Designing for Virtual Reality: 5 Lessons to Help You Get Started
Test driving a luxury car from the comfort of your couch. Getting on a rollercoaster that careens you through a world seething with fire-breathing dragons. Experiencing a spacewalk just as an astronaut would, floating 250 feet above the Earth. Today, these otherwise unimaginable experiences are all possible in virtual reality. The post An Introduction to Designing for Virtual Reality: 5 Lessons to Help You Get Started appeared first on Distillery. -
Equivalents in Python and JavaScript. Bonus
From time to time I google for the right syntax how to process lists and dictionaries in Python or arrays and objects in JavaScript. So I decided to extend my series of equivalents with those functions. After all, it's me too, who will be using the information I provide here. All truthful elements Sometimes we need to check from a list of conditions if all of them are true, or from a list of elements if all of them are not empty. This can be checked with the following in Python: items = [1, 2, 3]all_truthy = all(items)# True And here is an equivalent in JavaScript: items = [1, 2, 3];all_truthy = items.every(Boolean);// true Any truthful elements Similarly, we can check if at least one of the conditions is true, or there is at least one non-empty element in a list. It Python we would do that with: items = [0, 1, 2, 3]some_truthy = any(items)# True And in JavaScript we would check it like this: items = [0, 1, 2, 3];some_truthy = items.some(Boolean);// true Iterate through each element and its index Here is an example of how to iterate through a list of items and also check their indices … -
A Guide To Creating An API Endpoint With Django Rest Framework
As part of our work to make sharp web apps at Caktus, we frequently create API endpoints that allow other software to interact with a server. Oftentimes this means using a frontend app (React, Vue, or Angular), though it could also mean connecting some other piece of software to interact with a server. A lot of our API endpoints, across projects, end up functioning in similar ways, so we have become efficient at writing them, and this blog post gives an example of how to do so. First, a few resources: read more about API endpoints in this previous blog post and review documentation on Django Rest Framework. A typical request for an API endpoint may be something like: 'the front end app needs to be able to read, create, and update companies through the API'. Here is a summary of creating a model, a serializer, and a view for such a scenario, including tests for each part: Part 1: Model For this example, we’ll assume that a Company model doesn’t currently exist in Django, so we will create one with some basic fields: # models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) website = … -
How to test Django with LiveServerTestCase
When it comes to backend my tools of choice are Django and Python. Speed of development (particulary useful for rapid prototyping) and the excellent test coverage I can get almost out of the box are the major boons for me. I use Django for training aspiring developers too and when I run a workshop I don't go straight to the "right implementation". What I like instead is guiding newcomers through the initial "working implementation" to refactoring into a more complex application. In this tutorial you'll build a small application with the exact same mindset. We'll make it work first and them we will refactor for adding more features. How to test a Django application: what you will learn In the following tutorial you'll learn: how to build a simple Django website how to test a Django application how to measure test coverage How to test a Django application: requirements To follow along with the tutorial you should have: a basic understanding of Python and Django a newer version of Python installed on your system (Python 3 is nice to have) a basic understanding of both unit testing and functional testing How to test a Django application: setting up a Python … -
Implementation of single sign on using auth0 in django application
As the no of applications increases, users need to create username & passwords, need to remember for each application. Users can't remember these details and, sometimes users use single username/password for all applications, then there may be a chance of hacking your accounts easily. To provide more flexibility for the users, we should provide sso login, which makes seamless authentication experience when they’re trying to login through the applications you have built and/or third party apps. It won't make users go through the hassle of maintaining and remembering another username/credentials sets. In this blog post, we’ll see how to add single sign on & single sign out for a django application using auth0. Steps to follow for an auth0 account: Create your account in auth0 Go to applications & click on create application by proving app name(for ex: demoapp) & application type(web or mobile app etc.) Go to settings tab of your application(demoapp), you can see client id, client secret, domain values. Add application domains with a comma separated list in Allowed Web Origins & Allowed Origins (CORS) tab For ex: http://demoapp.io, http://demoauth.io By Default, application will use Username Password authentication database. We can also use custom database based on … -
Voice Tech 101: Everything You Need to Know About Voice User Interface
Interface design enables humans to interact with technology. Excitingly, voice user interfaces are fundamentally changing how we interact with many of our devices. Whether you’re new to voice technology or you’ve already gotten your feet wet, this “everything you need to know” primer gives a high-level overview of the various benefits and challenges of voice. These benefits and challenges will be driving forces in shaping the future of voice user interfaces. To get started, however, let’s first examine how voice interface design is different — and why that’s revolutionary. The post Voice Tech 101: Everything You Need to Know About Voice User Interface appeared first on Distillery. -
Make Django's collectstatic command forgiving
Have this ever happened to you, you run a python manage.py collecstatic command, it progresses for some time and then throws an error, something like ValueError: The file 'theme/startup/css/font/ytp-regular.eot' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x10b47cc50>? Well, that ... Read now -
7 Conferences We’re Looking Forward To
Above: The Internet Summit in Raleigh is one of the local conferences we recommend attending. (Photo by Ian Huckabee.) At Caktus, we strongly believe in professional development and continued learning. We encourage our talented team to stay up to date with industry trends and technologies. During 2018, Cakti attended a number of conferences around the country. Below is a list (in alphabetical order) of the ones we found the most helpful, practical, and interesting. We look forward to attending these conferences again, and if you get the chance, we highly recommend that you check them out as well. All Things Open Recommended by Account Executive Tim Scales Next Conference Location: Raleigh Next Conference Date: October 13 - 15, 2019 All Things Open is a celebration and exploration of open source technology and its impact. Topics range from nuts and bolts sessions on database design and OSS languages to higher-level explorations of current trends like machine learning with Python and practical blockchain applications. The annual conference is heavily publicized in the open source community, of which Caktus is an active member. All Things Open attracts open source thought leaders from across industries, and it’s a valuable learning experience for both non-technical …