Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Episode 2 - Enter With URLs
On this episode, we discuss Django’s front door, URLs. We talk about what URLs are, how to build them in Django, and the functions Django provides to work with URLs. Listen at djangoriffs.com. What’s a URL? A URL is a Uniform Resource Locator. It is the full address that goes into a browser. Consider https://www.mattlayman.com/django-riffs/. Here are the parts: Scheme, https:// Domain name: Top Level Domain (TLD), com Domain, mattlayman Subdomain, www Path or route, /django-riffs/ URLconf Every route for Django to handle goes into a URL configuration, URLconf for short and in the documentation. -
Episode 1 - Get To Know Django
Welcome to the show notes for the first episode of Django Riffs! Django Riffs is a podcast for learning web application development in Python using the Django web framework. Listen at djangoriffs.com. Who Is This For? This podcast is for absolute Django beginners. No prior knowledge of Django or web development is expected. Experienced users may learn something new or get a good refresher from topics they might have missed in the documentation. -
GeoDjango - Anna Kiefer
Weekly DjangoChat newsletterAnna Kiefer personal siteDjangoCon US 2018 - The Power of GeoDjango by Anna KieferGeoDjango docsPostGIS -
How to deploy Django project to Dokku with Docker
In this post, I will talk about how to deploy Django project to Dokku with Docker. -
How to deploy Django project to Dokku with Docker
In this post, I will talk about how to deploy Django project to Dokku with Docker. -
Moving to Django 3.0's Field.choices Enumeration Types
One of the headline features of Django 3.0 is its Enumerations for model field choices. They’re a nicer way of defining and constraining model Field.choices. Previously, Django recommended defining some ‘constants’ on your model class to feed into choices. You would add these as separate class variables and combine them into a list of choices paired with their display strings: from django.db import models class Book(models.Model): UNPUBLISHED = 'UN' PUBLISHED = 'PB' STATUS_CHOICES = [ (UNPUBLISHED, 'Unpublished'), (PUBLISHED, 'Published'), ] status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=UNPUBLISHED, ) Then your other could use those constants, for example: unpublished_books = Book.objects.filter(status=Book.UNPUBLISHED) If you wanted to use the same set of values for multiple models, you would probably move to the module level: from django.db import models UNPUBLISHED = 'UN' PUBLISHED = 'PB' STATUS_CHOICES = [ (UNPUBLISHED, 'Unpublished'), (PUBLISHED, 'Published'), ] class Book(models.Model): status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=UNPUBLISHED, ) class Pamphlet(models.Model): status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=PUBLISHED, ) This leaves a bunch of constants related only by their position in the class or module. It’s a bit against The Zen of Python’s final edict: Namespaces are one honking great idea – let’s do more of those! It also leaves us missing some … -
Guest Post: Sending Emails with Django
This is a guest post by Mailtrap.io team. The original post on Sending emails with Django was published at Mailtrap's blog. Some time ago, we discovered how to send an email with Python using smtplib, a built-in email module. Back then, the focus was made on the delivery of different types of messages via SMTP server. Today, we prepared a similar tutorial but for Django. This popular Python web framework allows you to accelerate email delivery and make it much easier. And these code samples of sending emails with Django are going to prove that. A simple code example of how to send an email Let's start our tutorial with a few lines of code that show you how simple it is to send an email in Django. Import send_mail at the beginning of the file from django.core.mail import send_mail And call the code below in the necessary place. send_mail( "That's your subject", "That's your message body", "from@yourdjangoapp.com", ["to@yourbestuser.com"], fail_silently=False,) These lines are enclosed in the django.core.mail module that is based on smtplib. The message delivery is carried out via SMTP host, and all the settings are set by default: EMAIL_HOST: "localhost"EMAIL_PORT: 25EMAIL_HOST_USER: (Empty string)EMAIL_HOST_PASSWORD: (Empty string)EMAIL_USE_TLS: FalseEMAIL_USE_SSL: False You … -
Django News - Issue 7 - Jan 24th 2020
News Announcing the Django Software Foundation Store: Featuring custom t-shirts, prints, and more The Django Software Foundation, the non-profit behind Django, has launched an official merchandise store. All proceeds benefit Django. threadless.com Have you checked out the Django Forum? The Django Forum is a place for discussing the Django framework and applications and projects that use it. The goal of the forum is to be a useful addition for lower-impact, more real-time discussion than Django's mailing lists. djangoproject.com Amazon Lightsail expands selection of instance blueprints Lightsail is Amazon’s VPS service; a “blueprint” is a pre-configured instance. Like a DigitalOcean “droplet”. So this is a pre-configured Django instance. amazon.com Sponsored Links Test-Driven Development with Django, Django REST Framework, and Docker From the popular TestDriven.io site, an updated course on how to build, test, and deploy a Django app with Docker, Pytest, and Django REST Framework! testdriven.io Articles Feature Checking versus Version Checking - Adam Johnson An analysis of whether to check for features in a new version of, say, Django, or to explicitly check the version number instead. Well-written and useful. adamj.eu How to create a Django project from a template A Django project template is the natural solution when the … -
Flask v Django: Bare to Production ~ Code Showdown
Hey there, In this video, I... -
OpenCV & Python: Exact Faces with a REST API
We're going to build a REST AP... -
Security Releases
Weekly DjangoChat NewsletterDjango News newsletterdjango-announce Google groupOfficial Django blog -
Introducing Django ClearCache - allows to clear cache via admin UI or command line
I've been working with the Django cache recently. And while Django has exceptional caching capabilities, I was surprised to find out that it doesn't provide a simple way to manually clear a cache. I checked online and found a couple of clear cache packages for Django, but all of them … Read now -
Django's Field Choices Don't Constrain Your Data
This post is a PSA on the somewhat unintuitive way Field.choices works in Django. Take this Django model definition: from django.db import models class Status(models.TextChoices): UNPUBLISHED = 'UN', 'Unpublished' PUBLISHED = 'PB', 'Published' class Book(models.Model): status = models.CharField( max_length=2, choices=Status.choices, default=Status.UNPUBLISHED, ) def __str__(self): return f"{self.id} - {Status(self.status).label}" If we open up a shell to manipulate them, we can easily create a Book with a given status choice: $ python manage.py shell # with ipython installed ... In [1]: from core.models import Status, Book In [2]: Book.objects.create(status=Status.UNPUBLISHED) Out[2]: <Book: 1 - Unpublished> The choices list constrains the value of status during model validation in Python: In [3]: book = Book.objects.get(id=1) In [4]: book.status = 'republished' In [5]: book.full_clean() --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-7-e64237e0a92a> in <module> ----> 1 book.full_clean() .../django/db/models/base.py in full_clean(self, exclude, validate_unique) 1220 1221 if errors: -> 1222 raise ValidationError(errors) 1223 1224 def clean_fields(self, exclude=None): ValidationError: {'status': ["Value 'republished' is not a valid choice."]} This is great for ModelForms and other cases using validation. Users can’t select invalid choices and get messaging about what’s wrong. Unfortunately, it’s still easy for us, as developers, to write this invalid data to the database: In [6]: book.save() Woops! It’s … -
Having some fun with Python
The other day on a Slack I hang out in, someone posted an amusing line of Python code: port = "{port}:{port}".format(port=port) If it’s not clear after the inevitable Swedish-chef-muppet impression has run through your mind, this string-formatting operation will replace the contents of port with a string containing two copies of whatever was in port, separated by a colon. So if port was "foo", now it will … Read full entry -
Django Quiz 4
On Wednesday evening last week I held a quiz at the January London Django Meetup Group. This was the fourth quiz, which has become an annual Christmas tradition at the meetup. Unfortunately it was a month late this year due to venue changes, so I’ve titled this post “Django Quiz 4”. Here it is so you can try it at home - answers are at the bottom. Enjoy! Part 1: Trivia 1. What creature is the Django pony? Unicorn Pegasus Horse Centaur 2. In which city will DjangoCon Europe 2020 be held? Prague, Czechia Porto, Portugal London, UK Vatican City 3. What is the “code word” for the latest major Django release? “Salmagundi” “Smorgasbord” “Raft” “Range” 4. What is the Django Software Foundation funding goal for 2020 in US Dollars? $30,000 $200,000 $600,000 $1,000,000 5. What was the name of one of Django Reinhardt’s cousins? Ruby Python ECMAScript Pascal Part 2: Coding in Django 6. The Django tutorial has you build a Django app called what? quizzes surveys polls testimonies 7. What is the date for the final Python 2.7 minor version release? April 2019 October 2019 January 2020 April 2020 8. According to crawler.ninja on 2020-01-14, what percentage of … -
How to Use Chart.js with Django
Chart.js is a cool open source JavaScript library that helps you render HTML5 charts. It is responsive and counts with 8 different chart types. In this tutorial we are going to explore a little bit of how to make Django talk with Chart.js and render some simple charts based on data extracted from our models. Installation For this tutorial all you are going to do is add the Chart.js lib to your HTML page: <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> You can download it from Chart.js official website and use it locally, or you can use it from a CDN using the URL above. Example Scenario I’m going to use the same example I used for the tutorial How to Create Group By Queries With Django ORM which is a good complement to this tutorial because actually the tricky part of working with charts is to transform the data so it can fit in a bar chart / line chart / etc. We are going to use the two models below, Country and City: class Country(models.Model): name = models.CharField(max_length=30) class City(models.Model): name = models.CharField(max_length=30) country = models.ForeignKey(Country, on_delete=models.CASCADE) population = models.PositiveIntegerField() And the raw data stored in the database: cities id name country_id population … -
Django News - Issue 6 - Jan 17th 2020
News HTTPX Release HTTPX is a next-generation HTTP client, likely the successor to the popular requests package. This latest release of HTTPX supports both sync and async and is one step away from a forthcoming 1.0 release. Django Newsletter Django Day Copenhagen 2020 - April 17, 2020 The call for participation is currently out for this one day Django conference. djangoday.dk DjangoCon Europe Early Bird Tickets Now Available The conference is in Porto, Portugal from May 27-31, featuring 3 days of talks and 2 days of springs. djangocon.eu Articles Advice for new contributors from the Django documentation There are many ways to contribute to Django itself, especially the documentation. Here is a getting-started guide. If you have any issues, put a question on the Django Forum and you'll get help! djangoproject.com Make Django Tests Always Rebuild the Database if It Exists - Adam Johnson An elegant quick fix for a common Django issue. adamj.eu Counting Queries: Basic Performance Testing in Django - Vinta Building Beyond Blog A nice overview of first-pass performance testing in a Django app. vinta.com.br Videos Django REST Framework Full Course for Beginners A 2+ hour course on building APIs with Django 3.0. youtu.be DjangoCon 2019 - … -
Demos, Prototypes, and MVPs
Much of my work at Hangar involves early product development, helping our startups “break ground” on their products. We’re starting with little more than an idea, and maybe some theories from the research, and taking the first steps towards a marketable product. I’m usually building one of three things: a demo, a prototype, or a minimum viable product (MVP). I’ve seen some confusion over these terms — some people seem to use them somewhat interchangeable. -
Django's Async Future - Tom Christie
Weekly DjangoChat NewsletterTom Christie personal siteEncodeDjangoCon Europe 2019 - Sketching out a Django redesignDjangoCon US 2019 - Just Add Await: Retrofitting Async into DjangoDjango REST FrameworkMkDocsmkautodocHTTPXurllib3Starlettehostedapi - demo app built with Starlette -
Asynchronous tasks in Django with Django Q
Learn how to use Django Q, the task queue, with the Redis broker for offloading long running tasks in your Django applications. Requirements To follow along you’ll need: an Heroku account if you want to use their Redis add-onthe Heroku CLI installed on your systema newer version of Python, ideally 3.6 or 3.7Git Deployment on Heroku is optional, and you can use your own Redis instance if you’ve already got one locally. Setting up the project And now let’s get to work! To start off we’re going to create a new Python virtual environment alongside with a Django installation: mkdir django-q-django && cd $_ python3 -m venv venv source venv/bin/activate pip install django Next up we’re going to create a new Django project from a template: django-admin startproject \ --template https://github.com/valentinogagliardi/ponee/archive/master.zip \ --name=Procfile \ --extension=py,example django_q_django . If you’re wondering what I’m doing here, this is a template of mine. I’ve got a link in the resources with a tutorial for creating your own Django project template. Now let’s install the dependencies with pip: pip install -r ./requirements/dev.txt We need also to provide some environment variables for our project: mv .env.example .env and finally we’re going to run Django migrations: … -
Asynchronous tasks in Django with Django Q
Requirements To follow along you'll need: an Heroku account if you want to use their Redis add-on the Heroku CLI installed on your system a newer version of Python, ideally 3.6 or 3.7 Git Deployment on Heroku is optional, and you can use your own Redis instance if you've already got one locally. Setting up the project And now let's get to work! To start off we're going to create a new Python virtual environment alongside with a Django installation: mkdir django-q-django && cd $_ python3 -m venv venv source venv/bin/activate pip install django Next up we're going to create a new Django project from a template: django-admin startproject \ --template https://github.com/valentinogagliardi/ponee/archive/master.zip \ --name=Procfile \ --extension=py,example django_q_django . If you're wondering what I'm doing here, this is a template of mine. I've got a link in the resources with a tutorial for creating your own Django project template. Now let's install the dependencies with pip: pip install -r ./requirements/dev.txt We need also to provide some environment variables for our project: mv .env.example .env and finally we're going to run Django migrations: python manage.py makemigrations python manage.py migrate at this point you should be able to run the development server: python … -
Django 3 Tutorial & CRUD Example with MySQL and Bootstrap
Django 3 is released with full async support! In this tutorial, we'll see by example how to create a CRUD application from scratch and step by step. We'll see how to configure a MySQL database, enable the admin interface, and create the django views. We'll be using Bootstrap 4 for styling. You'll learn how to: Implement CRUD operations, Configure and access a MySQL database, Create django views, templates and urls, Style the UI with Bootstrap 4 Django 3 Features Django 3 comes with many new features such as: MariaDB support: Django now officially supports MariaDB 10.1+. You can use MariaDB via the MySQL backend, ASGI support for async programming, Django 3.0 provides support for running as an ASGI application, making Django fully async-capable Exclusion constraints on PostgreSQL: Django 3.0 adds a new ExclusionConstraint class which adds exclusion constraints on PostgreSQL, etc. Prerequisites Let's start with the prerequisites for this tutorial. In order to follow the tutorial step by step, you'll need a few requirements, such as: Basic knowledge of Python, Working knowledge of Django (django-admin.py and manage.py), A recent version of Python 3 installed on your system (the latest version is 3.7), MySQL database installed on your system. We will … -
Make Django Tests Always Rebuild the Database if It Exists
If you use Django’s test runner, you’ll probably have encountered this message: $ python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "myproject_test" already exists Type 'yes' if you would like to try deleting the test database 'myproject_test', or 'no' to cancel: The main reason this happens is that the last test run crashed and it left the database around. It can be annoying when you start the test run, go for a cup of tea, and come back to this prompt still waiting, rather than a complete test run. Here’s how to make Django always rebuild the database in this case. We’ll do it by extending test with our own custom managemment command. Create a new test management command inside one of your Django apps, for example testapp/management/commands/test.py. Then add this content: from django.core.management.commands.test import Command as BaseCommand class Command(BaseCommand): def handle(self, *test_labels, **options): # Wrap Django's built-in test command to always delete the database if # it exists options["interactive"] = False return super().handle(*test_labels, **options) This works by intercepting the normal handle() method to first always set the interactive option to False. This is the same as always passing the --noinput … -
How to have default/initial values in a Django form that is bound and rendered
Django's Form framework is excellent. It's intuitive and versatile and, best of all, easy to use. However, one little thing that is not so intuitive is how do you render a bound form with default/initial values when the form is never rendered unbound. If you do this in Django: class MyForm(forms.Form): name = forms.CharField(required=False) def view(request): form = MyForm(initial={'name': 'Peter'}) return render(request, 'page.html', form=form) # Imagine, in 'page.html' that it does this: # <label>Name:</label> # {{ form.name }} ...it will render out this: <label>Name:</label> <input type="text" name="name" value="Peter"> The whole initial trick is something you can set on the whole form or individual fields. But it's only used in UN-bound forms when rendered. If you change your view function to this: def view(request): form = MyForm(request.GET, initial={'name': 'Peter'}) # data passed! if form.is_valid(): # makes it bound! print(form.cleaned_data['name']) return render(request, 'page.html', form=form) Now, the form is bound and the initial stuff is essentially ignored. Because name is not present in request.GET. And if it was present, but an empty string, it wouldn't be able to benefit for the default value. My solution I tried many suggestions and tricks (based on rapid Stackoverflow searching) and nothing worked. I knew one thing: … -
How to have default/initial values in a Django form that is bound and rendered
Django's Form framework is excellent. It's intuitive and versatile and, best of all, easy to use. However, one little thing that is not so intuitive is how do you render a bound form with default/initial values when the form is never rendered unbound. If you do this in Django: class MyForm(forms.Form): name = forms.CharField(required=False) def view(request): form = MyForm(initial={'name': 'Peter'}) return render(request, 'page.html', form=form) # Imagine, in 'page.html' that it does this: # <label>Name:</label> # {{ form.name }} ...it will render out this: <label>Name:</label> <input type="text" name="name" value="Peter"> The whole initial trick is something you can set on the whole form or individual fields. But it's only used in UN-bound forms when rendered. If you change your view function to this: def view(request): form = MyForm(request.GET, initial={'name': 'Peter'}) # data passed! if form.is_valid(): # makes it bound! print(form.cleaned_data['name']) return render(request, 'page.html', form=form) Now, the form is bound and the initial stuff is essentially ignored. Because name is not present in request.GET. And if it was present, but an empty string, it wouldn't be able to benefit for the default value. My solution I tried many suggestions and tricks (based on rapid Stackoverflow searching) and nothing worked. I knew one thing: …