I have finished Python Crash Course book recently. And especially liked its second part with real projects. Book content is a little bit out-dated (2015), so I decided to post some notes about making Learning Log web application code to work with Django 2.x.
The very first issue is that in Django 2.x you must specify on_delete rule. You’ll get it during Entry creation class. Any time you create ForeignKey don’t forget to specify on_delete parameter, for example:
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
By default Django 2 uses path instead of url. The difference is very minor:
path('', include('learning_logs.urls', namespace='learning_logs')),
url(r'', include('learning_logs.urls', namespace='learning_logs')),
But when path parameters are involved path is much more simpler! You don’t need any regular expressions anymore:
path('topics/<int:topic_id>/', views.topic, name='topic'),
To use namespaces you need to specify app_name property now. It must be defined for any app in urls.py before urlpatterns list. For example this is my learning_logs/urls.py:
from django.urls import path
from django.conf.urls import url
from . import views
app_name = 'learning_logs'
urlpatterns = [
path('', views.index, name='index'),
path('topics/', views.topics, name='topics')
Default search path for templates has changed and you don’t have to prepend template path with app prefix anymore. In other words instead of ‘learning_log/base.html’ use ‘base.html’. Otherwise Django will fail with detailed error page and list of searched folders.
All steps for configuring my project for Heroku worked OK except code change change to automatically identify Heroku environment in settings.py. I was forced to ask StackOverflow and official Heroku guide 🙂
So the first thing is to define environment variable which will be used to detect Heroku! Type this command in your shell for that:
heroku config:add I_AM_HEROKU=yes
Then it can be used to automatically configure our app for Heroku by adding following code ar the end of your settings.py:
if os.environ.get('I_AM_HEROKU') == 'yes':
DEBUG = False
That’s it! No more tricks 🙂 My project code is available on GitHub.