Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django properties from expressions, or ComputedField part 2
I've discussed the concept of a [ComputedField](https://schinckel.net/2018/11/12/django-computedfield(\)) in the past. On the weekend, a friend pointed me towards SQL Alchemy's [Hybrid Attributes](https://docs.sqlalchemy.org/en/13/orm/extensions/hybrid.html). The main difference here is that in a ComputedField, the calculation is always done in the database. Thus, if a change is made to the model instance (and it is not yet saved), then the ComputedField will not change it's value. Let's look at an example from that original post: {% highlight python %} class Person(models.Model): first_name = models.TextField() last_name = models.TextField() display_name = ComputedField( Concat(F('first_name'), Value(' '), F('last_name')), output_field=models.TextField() ) {% endhighlight %} We can use this to query, or as an attribute: {% highlight python %} Person.objects.filter(display_name__startswith='foo') Person.objects.first().display_name {% endhighlight %} But, if we make changes, we don't see them until we re-query: {% highlight python %} person = Person(first_name='Fred', last_name='Jones') person.display_name # This is not set {% endhighlight %} So, it got me thinking. Is it possible to turn a django ORM expression into python code that can execute and have the same output? And, perhaps the syntax SQL Alchemy uses is nicer? {% highlight python %} class Person(models.Model): first_name = models.TextField() last_name = models.TextField() @shared_property def display_name(self): return Concat( F('first_name'), Value(' '), F('last_name'), output_field=models.TextField(), … -
Redis on Windows
Redis is a very popular data s... -
django-tree-queries
django-tree-queries The reason for this blog post is the recent release of django-tree-queries 0.4. django-tree-queries allows using an SQL database to retrieve tree nodes in depth-first search (DFS) order. Other libraries Many Django libraries exist already for managing and retrieving tree-shaped data. A list of them follows along with reasons why none of them are being used in feincms3. django-mptt I still am a heavy user of django-mptt. FeinCMS 1.x uses it and we therefore use django-mptt as well for many sites which are actively maintained. I also am a co-maintainer of django-mptt so the following critique should be understood with this fact in mind. django-mptt uses the nested set model with an additional level and tree_id field; the latter partitions nodes into individual, unconnected trees. This is a useful performance optimization. In principle, the nested set model doesn’t even require a parent foreign key for nodes; however, django-mptt always adds this field as well. django-mptt is very dependent on having up-to-date values of the left, right and parent_id values. Fetching ancestors or descendants does not work when those values are outdated. Calling .save() with outdated values absolutely will cause corrupted trees – that is, the MPTT attributes get out … -
From Concept To Live In Two Weeks With Django
My team had two weeks to make a viable product. We were a random group of people pulled together with a desire to help our local community in Frederick, Maryland. We were a student, a web designer, a former realtor turned IT support person, and a software developer. Our mission, which was put forth by the virtual hackathon that brought us together, was to try to make a tool to help the local homeless. -
Understanding the Application and Request Contexts in Flask
This post provides clarity on how the Application and Request contexts work in Flask. -
Slugify Urls in Django
In this tutorial, we will learn how to slugify urls in Django. -
Measuring Hiring Manager Effectiveness
Hiring is one of the most important parts of a manager’s job. Make good hires and your team (and thus the whole company) will have better results. Make poor hires, and those people will drag the team down. In the worst cases, a toxic hire can drive other staff to quit, totally destroying the team. Strangely, for such an important part of the job, hiring performance seems to be very poorly measured. -
Google-cloud & Heroku
I have just setup a Django website on Heroku. That was fairly easy. One of the "gotcha" was the Google-cloud authentication. Getting access to Google translate took a bit more work than other APIs. Here is how I've done it. -
Google-cloud & Heroku
I have just setup a Django website on Heroku. That was fairly easy. One of the "gotcha" was the Google-cloud authentication. Getting access to Google translate took a bit more work than other APIs. Here is how I've done it. -
Using environment variables to configure Django
Using environment variables to configure Django My preferred way to read values from the environment uses the ast module to evaluate Python literals. This means that values such as ["*"], None and True aren’t returned as strings but actually have the expected type already. A basic implementation using ast.literal_eval() follows: import ast import os def env(key): value = os.environ[key] try: return ast.literal_eval(value) except (SyntaxError, ValueError): return value Some deployment environments may not make it easy to add environment variables. I like placing a .env file into the project root containing additional key-value combinations. Here’s a way to add those values to the environment: def read_speckenv(): with open(".env") as f: for line in f: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = [v.strip("'\" \t") for v in line.split("=", 1)] os.environ.setdefault(key, value) Those two functions along with a few additional bells and whistles are available as speckenv from PyPI. The packaged version also supports defaults, warning messages, coercion and using another mapping instead of os.environ. The implementation follows the basics outlined above. Of course it may be useful to bundle the conversion of DSNs to the configuration format Django expects, however I mostly … -
Upload Images to Cloudinary from Django Application
Upload images to Cloudinary from Django Application. -
Image processing and server crashes with Django
Image processing and server crashes with Django The default ImageField model and form fields do not verify that Pillow is able to actually process the image file at all. They only verify the image files’ headers. This is by design, since processing full images opens websites up to denial of service attacks. The downside of this is that thumbnailing libraries have to guard against all sorts of invalid images. If they do not do this thoroughly an invalid (e.g. truncated) image file may crash a whole website. The worst which can happen (and this has happened to me a few times) is that it may even be impossible to replace the invalid image through the administration panel, because the customized admin widget also crashes while generating a thumbnail. Now you need a programmer with access to the database to even be able to replace the image. And maybe the website editors upload the invalid image again… Anyway, these experiences lead me to repeatedly researching solutions and in the end, in the spirit of the following XKCD comic I set out to write my own image field. The result of this work is django-imagefield. It has the following differentiating features: In-depth … -
Onnx Machine Learning in Production
I recently had a project that ... -
Django Signup Tutorial
Previously we [added login and logout pages](https://learndjango.com/tutorials/django-login-and-logout-tutorial) to our Django app. In this tutorial we'll create a sign up page so users can register for a new account. The [Django … -
Django News - PyConline AU Talks Now Live! - Sep 11th 2020
News Django Technical Board Candidate Registration Registration for Candidates will end on September 11th, 2020 AoE. djangoproject.com Django-Developers Discussion: Generate JWTs with Django django-developers is the official Google Group for discussion of Django technical features and recently questions around JWTs were discussed. google.com Events DjangoCon Europe Schedule is out! September 18 & 19 Note that the timezone is GMT+1 djangocon.eu DjangoCon Europe 2020 Tickets DjangoCon Europe 2020 is one week away! pretix.eu PyGotham TV's schedule is out! October 2 & 3 PyGotham TV's schedule is out and is free to attend. pygotham.tv Articles Django Hosting & Deployment Options Will Vincent does a rundown on popular Platform-as-a-service (PaaS) and virtual private server (VPS) hosting/deployment options for Django. learndjango.com From Concept To Live In Two Weeks With Django Matt Layman's very good rundown of building a Django + Tailwind CSS + Heroku project for a non-profit in only 2 weeks. mattlayman.com What happens when you run manage.py test? Adam Johnson's PyConAU talk which details Django testing internals. Complements his PyConAU talk in the Videos section. adamj.eu Demystifying Django’s Magic Precious Ndubueze's overview of what Django brings to the table as a web framework. smashingmagazine.com Videos PyConline AU 2020 The full PyConline AU … -
Not all attacks are equal: understanding and preventing DoS in web applications
Denial-of-Service (DoS) vulnerabilities are common, but teams frequently disagree on how to treat them. The risk can be difficult to analyze: I’ve seen development teams argue for weeks over how to handle a DoS vector. This article tries to cut through those arguments. It provides a framework for engineering and application security teams to think about denial-of-service risk, breaks down DoS vulnerabilities into high-, medium-, and low-risk classes, and has recommendations for mitigations at each layer. -
Displaying Breaks - Building SaaS #72
In this episode, I worked to add breaks to the display of the week schedule. We had to update context to include the break information into the schedules. I refactored a method out of the calendar display code to make some reusable logic for handling breaks. The app needs to display breaks on the schedule and adjust what is displayed based on when the breaks are. I started with changing the background color of the break days. -
Episode 8 - Administering Your App
On this episode, we will focus on the built-in Django administrator’s site. We’ll see what it is, how you can configure it, and how you can customize it to serve your needs. Listen at djangoriffs.com. Last Episode On the last episode, we explored more about models and how to interact with data in your database. What Is The Django Admin? Django includes a web administrative interface that can help programmers and non-programmers alike. -
Training Interviewers
What’s the best way to train folks to conduct job interviews? I have a process I’ve used for about five years that seems to work well. It’s loosely based on the “see one, do one, teach one” methodology used by many medical schools. Here’s what I do: 1. Training I’ll spend about an hour covering the practice of interviewing: how to ask questions and follow-ups, take notes, correct for unconscious bias, handle difficult situations, etc. -
Is Django a Full Stack Framework?
The title of this post, "Is Django a Full Stack Framework?" is a question I receive often from new web developers. It's a very valid question so I wanted to … -
How To Keep Your Custom Form Fields DRY
When building a custom form which yields a group of incremental fields several times over, we often manually create each group like the following:class ExampleForm(forms.Form): first_name_1 = forms.CharField(required=False) last_name_1 = ... -
How to Unit Test a Django Management Command
This post is an adapted extract from my book Speed Up Your Django Tests, available now. When we write custom management commands, it’s easy to write integration tests for them with call_command(). This allows us to invoke the management command as it runs under manage.py, and retrieve the return code, standard output, and standard error. It’s great, but has some overhead, making our tests slower than necessary. If we have logic separated out of the command’s handle() method, it improves both readability and testability, as we can unit test it separately. Example Command Take this management command, that implements some book title normalization rules: from django.core.management.base import BaseCommand from django.db.transaction import atomic from example.core.models import Book class Command(BaseCommand): help = "Normalize all Book titles" def add_arguments(self, parser): parser.add_argument( "--write", action="store_true", default=False, help="Actually edit the database", ) @atomic def handle(self, *args, write, **kwargs): if not write: self.stdout.write("In dry run mode (--write not passed)") books = Book.objects.select_for_update() for book in books: book.title = self.normalize_title(book.title) if write: Book.objects.bulk_update(books, ["title"]) self.stdout.write(f"Updated {len(books)} book(s)") def normalize_title(self, title): if not title: return "Unknown" if title[0].islower(): title = title[0].upper() + title[1:] if title.endswith("."): title = title[:-1] title = title.replace("&", "and") return title (These is the same logic … -
VS Code: Automatically Organize Python Imports
In this quick tip, we'll see how to configure VS Code to automatically organize Python imports upon saving your source code files. VS Code: Automatically Organize Python Imports You can configure VS Code to automatically sort and organize Python imports upon saving files. First need to install the isort package system-wide using the following command: $ pipenv install isort --dev Open the settings using ⇧⌘P or Ctrl+Shift+P, next search for Preferences: Configure Language Specific Settings.... Press Enter and then search for Python. In the settings.json file that will be opened, add the following settings: "[python]": { "editor.codeActionsOnSave": { "source.organizeImports": true } } Now upon saving files with the .py extension, VS Code will automatically sort and organize the imports. -
Run your Python Unit Tests with GitHub Actions
In this tutorial, we'll learn how to automatically run your Python unit tests using GitHub Actions. We'll see how to set up a GitHub Actions workflow that install Python 3.6 inside a Ubuntu system along with our project's dependencies e.g. pytest and finnaly run the unit tests after pushing our code to a GitHub repository. Let's see how to automate running unit tests when making a commit and pushing your code to GitHub or when making a pull request. Thanks to GitHub Actions it's now easier than before without using any external services and they even provide a good free tier. This will allow you to spot the right commit(s) that broke your code. We'll be using Python 3, and we will be working in a virtual environment. This is a good practice for Python to isolate system packages from our project's package. Even if this is a small example but should be a practice that you need to always follow. Let's start by creating and activating a virtual environment for our project, by running the following commands: $ mkdir pytestexample $ cd pytestexample $ python3 -m venv .env This will create a virtual environment called .env in our project's … -
How to Delete Local/Remote Git Branches
If you have previously worked with Git for versioning your Angular code, there is a good chance that you had some situation where you wanted to delete a remote branch or multiple branches. This happens many times to developers, particularly in large projects. In this article, we'll learn: How to delete a local branch in your Git repository, How to delete a remote branch in Git, How to delete all Git branches which have been merged, How to remove all local branches not on remote, How to delete all your local Git branches except master. Before tackling how to delete a remote branch, we’ll first see how to delete a branch in the local Git repository. Note: Version control systems are an indispensable tool in modern web development that can help you solve many issues related to every task. Git is one of the most popular version control systems nowadays. Before we proceed to learn how to delete local and remote branches in Git, let's define what's a Git branch and the side effects of deleting branches. A branch in Git is a pointer to a commit. If you delete a branch, it deletes the pointer to the commit. This …