Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Using Django Check Constraints to Limit the Range of an IntegerField
Another way to use database constraints via Django’s CheckConstraint class. A classic bit of data validation is to check input values lie within the expected range. This can prevent obvious data accidents, such as the NHS recently recording a journalist’s height as 6cm, and thus calculating his BMI as 28,000(!). Django’s built-in numerical fields have ranges that match the limits that databases support. For example, IntegerField supports the range −2,147,483,648 (−231) to 2,147,483,647 (231 − 1). Most real world numbers lie in much more limited ranges, so we can have our application reject obviously wrong numbers. Example Imagine we have a Book model with a field for the page count, which we know only for some books. We know the page count cannot be negative, so we would use a PositiveIntegerField: from django.db import models class Book(models.Model): ... page_count = models.PositiveIntegerField(null=True) This is a great start but the maximum value of 231 − 1 is still really high. With a little bit of research we can find Wikipedia’s list of longest novels page. This pegs the longest (work-in-progress) novel at 22,400 pages (Venmurasu). If we round this figure up to 25,000 pages for our upper bound, we can reject outlandishly … -
Using Django Check Constraints to Limit the Range of an IntegerField
Another way to use database constraints via Django’s CheckConstraint class. A classic bit of data validation is to check input values lie within the expected range. This can prevent obvious data accidents, such as the NHS recently recording a journalist’s height as 6cm, and thus calculating his BMI as 28,000(!). Django’s built-in numerical fields have ranges that match the limits that databases support. For example, IntegerField supports the range −2,147,483,648 (−231) to 2,147,483,647 (231 − 1). Most real world numbers lie in much more limited ranges, so we can have our application reject obviously wrong numbers. Example¶ Imagine we have a Book model with a field for the page count, which we know only for some books. We know the page count cannot be negative, so we would use a PositiveIntegerField: from django.db import models class Book(models.Model): ... page_count = models.PositiveIntegerField(null=True) This is a great start but the maximum value of 231 − 1 is still really high. With a little bit of research we can find Wikipedia’s list of longest novels page. This pegs the longest (work-in-progress) novel at 22,400 pages (Venmurasu). If we round this figure up to 25,000 pages for our upper bound, we can reject outlandishly … -
Better usage of JS/CSS inside Django Templates with django-floppyforms
Introduction It's a good idea to make use of a modern Javascript framework such as VueJS, React or Angular, however, there are also many advantages using one single project where you have the backend (ORM, Services, Queue, Transactions and so on) and... -
Re-discovering Django
A few years ago I had a job where I mostly did Django development. The sites were mainly informational - a place to host text and pictures that were easy for non-technical people to edit. Primarily they were cookie-cutter replicas of previous websit... -
Django News - It's May. New Django, Python, and PyCon are next week. - May 7th 2021
News Django security releases issued: 3.2.2, 3.1.10, and 2.2.22 There were two Django security releases this week. Upgrade to the latest Django version to get them both. Django: 3.2.1, 3.1.9, and 2.2.21 - CVE-2021-31542: Potential directory-traversal via uploaded files Django 3.2.2, 3.1.10, and 2.2.22 - CVE-2021-32052: Header injection possibility since URLValidator accepted newlines in input on Python 3.9.5+ djangoproject.com PyCharm & DSF Campaign 2021 Results The fifth annual JetBrains PyCharm promotion in April netted the Django Software Foundation $45,000 this year, a slight increase over the $40,000 raised last year. djangoproject.com Python 3.8.10, 3.9.5, and 3.10.0b1 are now available The latest bug and security fixes for Python 3.8 and 3.9 along with the first Python 3.10 beta are available along blogspot.com Events PyCon 2021: Call for Volunteers! PyCon 2021 is next week! Please consider volunteering if you plan to attend. It's a great way to meet people and contribute back to our wonderful community. pycon.org PyCon AU 2021: CFP is open! PyConline AU's call for proposals (CFP) is open until 10 June, anywhere on earth. pycon.org.au Sponsored Link Senior Django Developer As a Senior Django Developer you’ll work alongside the CTO, fellow software engineers, product managers, and designers, to execute … -
Django - A python framework | 6 Hours Course
Django is the most famous Python web framework for perfectionists with deadlines. Let's learn Django by creating a Bookstore app with user authentication, file uploading, reviews on books and many more features https://www.youtube.com/watch?v=aY43fUG... -
Goals here:
I am new here. I will be writing about Python and Django plus other front-end frameworks as per the experience i have garnered for the past 5 years. I hope this blog will help someone out there. -
Monitoring Django applications
Every once in a while people reach out to me for advice on how to monitor their Django sites. How do you know when your site breaks? How do you fix things before your users notice? My answer: it depends. In this post I'll summarize the different monitoring methods I've found and used for Django projects. Some methods are language and platform agnostic - they apply if you are writing Rails or Node code, while others are specific to Django. ### Crowdsourced monitoring This is the simplest form of monitoring and the starter pack for every web developer. Simply wait until an angry user to tweets you that your site is offline and fix the bugs as the complaints come in.  **Pros**: cheap because it requires no work. **Cons**: humiliating and costly. You might lose customers. It's bad publicity. If your boss finds out, he might shout at you. Crowdsourced monitoring is best suited for hobby projects and startups, where uptime isn't important because your app isn't making money. Instead of building monitoring tools you can invest time in building features. Move fast and break things. ### Built in Django error reports Django is packaged with a lot … -
Pipenv Not Found on Windows 😖
To simply get started using pipenv on windows for your project instead of pip and the virtual environment separately follow the steps below First, uninstall the virtual environment with the command below through the terminal provided that python has... -
Django Views in Action
Welcome, So we have successfully performed CRUD Action with Django and it is time to show our visitors the students we have registered successfully and probably allow them to search for any registered student. In this article, we will Fetch all stud... -
3 uses for functools.partial in Django
Python’s functools.partial is a great tool that I feel is underused. (If you don’t know what partial is, check out PyDanny’s explainer.) Here are a few ways I’ve used partial in Django projects. 1. Making reusable fields without subclassing It’s common to have field definitions the same across many models, for example a created_at field tracking instance creation time. We can do create such a field like so: from django.db import models class Book(models.Model): created_at = models.DateTimeField( default=timezone.now, help_text="When this instance was created.", ) Copying this between models becomes tedious, and makes changing the definition hard. One solution to this repetition is to use a base model class or mixin. This is fine, but it scatters the definition of a model’s fields, prevents local customization of arguments, and can lead to complex inheritance hierarchies. Another solution is to create a subclass of DateTimeField and add it to every model. This works well but can lead to complications with migrations, as the migration files will refer to the subclass by import and we will need to update them all if we refactor. We can instead use partial to create a “cheap subclass” of the field class. Our models will still directly … -
3 uses for functools.partial in Django
Python’s functools.partial is a great tool that I feel is underused. (If you don’t know what partial is, check out PyDanny’s explainer.) Here are a few ways I’ve used partial in Django projects. 1. Making reusable fields without subclassing¶ It’s common to have field definitions the same across many models, for example a created_at field tracking instance creation time. We can do create such a field like so: from django.db import models class Book(models.Model): created_at = models.DateTimeField( default=timezone.now, help_text="When this instance was created.", ) Copying this between models becomes tedious, and makes changing the definition hard. One solution to this repetition is to use a base model class or mixin. This is fine, but it scatters the definition of a model’s fields, prevents local customization of arguments, and can lead to complex inheritance hierarchies. Another solution is to create a subclass of DateTimeField and add it to every model. This works well but can lead to complications with migrations, as the migration files will refer to the subclass by import and we will need to update them all if we refactor. We can instead use partial to create a “cheap subclass” of the field class. Our models will still directly … -
Dockerizing FastAPI with Postgres, Uvicorn, and Traefik
This tutorial details how to configure FastAPI to run on Docker along with Postgres, Uvicorn, Traefik, and Let's Encrypt. -
Fluent in Django: Get to know Django models better
Intro Django is an MTV framework. Instead of MVC (Model, Views, Controller), it uses Model, Template, and View. The View is a Python function that takes a Web request and returns a Web response (in MVC, this would be a Controller). But the heart of y... -
Disabling FLoC, Google’s new advertising technology
Google has started rolling out FLoC, currently to 0.5% of Chrome users, and some sites are already disabling it. In this post we’ll cover what FLoC is, who’s disabling it, why, and how to do so on a Django site. What is FLoC? FLoC stands for Federated Learning of Cohorts. It was developed by Google and at current only Chrome implements it. FLoC uses a machine learning model in the browser to transform your browsing history into a fingerprint. That fingerprint places you in a bucket of “a few thousand users worldwide”. Advertisers can use this to determine your interests without knowing exactly who you are. FLoC is an alternative to the many advertising providers tracking your browsing using third party cookies and building their own fingerprints. Browsers are gradually phasing out third party cookies, so advertisers are eager to have an alternative. Google has a key interest here, since they both make the most popular browser and sell the most ads. This feature is being rolled out incrementally across Chrome users, without any notification or opt-in. At time of writing, 0.5% of Chrome users are “being FLoCed”, with a fingerprint available to registered sites calling the JavaScript API document.interestCohort(). … -
Disabling FLoC, Google’s new advertising technology
Google has started rolling out FLoC, currently to 0.5% of Chrome users, and some sites are already disabling it. In this post we’ll cover what FLoC is, who’s disabling it, why, and how to do so on a Django site. What is FLoC?¶ FLoC stands for Federated Learning of Cohorts. It was developed by Google and at current only Chrome implements it. FLoC uses a machine learning model in the browser to transform your browsing history into a fingerprint. That fingerprint places you in a bucket of “a few thousand users worldwide”. Advertisers can use this to determine your interests without knowing exactly who you are. FLoC is an alternative to the many advertising providers tracking your browsing using third party cookies and building their own fingerprints. Browsers are gradually phasing out third party cookies, so advertisers are eager to have an alternative. Google has a key interest here, since they both make the most popular browser and sell the most ads. This feature is being rolled out incrementally across Chrome users, without any notification or opt-in. At time of writing, 0.5% of Chrome users are “being FLoCed”, with a fingerprint available to registered sites calling the JavaScript API document.interestCohort(). … -
How one default parameter almost killed our servers
<![CDATA[ How one default parameter almost killed our servers This is a story about an issue we had to fix in one of the projects I am involved with. I basically woke up to Slack messages from my colleague who discovered that a couple of servers were basically out of RAM and somehow still worked thanks to swap. I have to admit I am quite embarrassed by this mistake, but on the other hand web stuff is not my core competency (😃) and I want to share this as a cautionary tale. When investigating the issue, we quite quickly found that there were lot's of scripts launched by cron running simultaneously. In normal circumstances, this particular script would finish long before it would be launched again by cron. So something was keeping the scripts basically "stuck". And this was basically the reason why servers ran out of memory. Below is chart showing number of processes which does a great job of illustrating the issue we had: The drop is server restart and then hotfix patch. While the script is fairly involved, in a nutshell it does a few requests to external service and processes the result. It is written in … -
FYP-DevLog-007
Progress Highlights NOTE: This DevLog is a combination of my progress for both Week 7 and Week 8 Project Research Obtained approval from supervisor for final version of Table of Comparison Split master Table of Comparison (in Excel sheet) into 2 ta... -
Django Abstract Models
Image credit Unsplash Scenario 1 Fat models, skinny views Handle your business logic in models These are what are considered MVC best practices when it comes to writing Model-View-Controller architectures. But as your codebase grows from 10 lines... -
How to set the new COEP, COOP, and CORP security headers in Django
Here are three new security headers on the block: Cross-Origin-Opener-Policy (COOP) (MDN) Cross-Origin-Resource-Policy (CORP) (MDN) Cross-Origin-Embedder-Policy (COEP) (MDN) They don’t currently score you any points on the securityheaders.com checker, but they’re worth looking at to improve your site’s security. Let’s briefly look at what they do, Django’s future support for them, and how you can add them today. For a longer description see Scott Helme’s article and the above MDN links. Cross-Origin-Opener-Policy (COOP) COOP isolates your origin in its own browsing context group. A browsing context group is a set of documents that have references to each other, and thus live in the same memory space. COOP isolation prevents attacks like Spectre and Meltdown, which exploit flaws in CPU’s to read protected areas of the current memory space. Such attacks allow third party origins to steal your origin’s secrets, such as session cookies, because they share your browsing context group. The initial response from browsers to Spectre and Meltdown was to disable the JavaScript API’s necessary to execute the attacks. This meant disabling the high resolution clock performance.now() and the data-sharing API SharedArrayBuffer. Setting a secure COOP header allows your site to re-enable those features. Adding COOP comes at the … -
How to set the new COEP, COOP, and CORP security headers in Django
Here are three new security headers on the block: Cross-Origin-Opener-Policy (COOP) (MDN) Cross-Origin-Resource-Policy (CORP) (MDN) Cross-Origin-Embedder-Policy (COEP) (MDN) They don’t currently score you any points on the securityheaders.com checker, but they’re worth looking at to improve your site’s security. Let’s briefly look at what they do, Django’s future support for them, and how you can add them today. For a longer description see Scott Helme’s article and the above MDN links. Cross-Origin-Opener-Policy (COOP)¶ COOP isolates your origin in its own browsing context group. A browsing context group is a set of documents that have references to each other, and thus live in the same memory space. COOP isolation prevents attacks like Spectre and Meltdown, which exploit flaws in CPU’s to read protected areas of the current memory space. Such attacks allow third party origins to steal your origin’s secrets, such as session cookies, because they share your browsing context group. The initial response from browsers to Spectre and Meltdown was to disable the JavaScript API’s necessary to execute the attacks. This meant disabling the high resolution clock performance.now() and the data-sharing API SharedArrayBuffer. Setting a secure COOP header allows your site to re-enable those features. Adding COOP comes at the … -
Jason Learns Django - 08
And just like that, this little journey ends. Read more… (1 min remaining to read) -
Django News - PyPI PM and DjangoCon Europe Early Bird Tickets - Apr 30th 2021
News PSF News: The PSF is hiring a Python Packaging Project Manager! Thanks to a two-year grant commitment from Bloomberg, The Python Software Foundation (PSF) is hiring a full-time project and community manager for the Python Packaging ecosystem, with a specific focus on the Python Package Index (PyPI). blogspot.com Events DjangoCon Europe 2021 Early Bird Tickets End Today! Last call on DjangoCon Europe Early Bird Tickets. Sales end on April 30th. beamian.com Django London May Meetup You can submit to talk at this or a future event with this form: https://forms.gle/cXMDC43Ja5HSBvPy8 meetup.com Sponsored Link Migrating from Django 1.7 to 3.1 is no small task. Learn how to successfully leapfrog a massive Django/Python upgrade. sixfeetup.com Articles Fluent in Django: 8 Django Template Tags You Should Know Django comes with a number of built-in template tags and this article covers 8 less common but still very useful ones to know. girlthatlovestocode.com How to convert a TestCase from setUp() to setUpTestData() Django Technical Board member Adam Johnson shows how to convert your tests to speed up performance. adamj.eu PyDev of the Week: Haki Benita This week we welcome Haki Benita (@be_haki) as our PyDev of the Week! pythonlibrary.org Extending Django Wizards Demonstrates how … -
Switching databases in Django in production
There are times when you're done with the development stage in your Django web application, and you've got some sort of data in your db.sqlite3 database which you'd like to copy as-is to your new DB. Also it happens that you might want to switch data... -
Jason Learns Django - 07
Today was a little easier. Read more… (1 min remaining to read)