Django Version Changes and Transcript References
Most of the course videos were recorded in Django 2.2. At the beginner level, there is little difference between Django 2.2, 3.2 and 4.0, so rather than completely re-recording all the videos, I have updated the transcript below and annotated the video at key sections.
The video mentions copying code from the screen or transcript. I still recommend you type in the code yourself, so there is no code in the transcript below. If you do want to copy my code, you can get it from the source, which you can download here.
As we discussed in module 1, a Django model is a data object that maps your app’s data to the database without you having to know SQL, or how the underlying database structures your data. Each of your app’s models are a class that you create in your app’s
The Page Model
The easiest way to learn how models work is to create one—so let’s go ahead and create a Page model. Pause the video and enter this text into your editor or copy it from your transcript.
Now let’s take a closer look at the model, as a fair bit is going on here:
- In Line 1 we import the
django.db. If you used
startapp, this line will be in your file already.
- In Line 3 we create the
Pageclass, which must inherit from Django’s
- Then in lines 4 to 7, we define the fields for the model. These fields will have a corresponding field in the database table that Django creates for the model:
- Title. The title of your page. This will be put in the HTML title element of your template.
- Permalink. A permalink to an individual page.
- Update_date. The date the page was last updated. You use this field to keep track of page edits.
- And bodytext. The HTML content of your page. This will be put in the HTML body element of your template.
Each of our model fields has a related Django field type and field options. The
Page model uses three different field types—
TextField. Let’s have a look at the field types and options in more detail:
- Title is a
CharFieldis a short line of text (up to 255 characters). In this case, the
max_lengthoption sets the maximum length of the page title to 60 characters.
- Permalink is another
CharField. As in the title field, the permalink field has a
max_lengthoption set, but for the permalink, the length is limited to 12. permalink also has an additional option:
unique=True. As we are using the permalink to create a URL to the page, we don’t want the permalink to be duplicated, so this option ensures that an error will be thrown if you try to enter the same permalink for two pages.
DateTimeFieldrecords a Python
datetimeobject. Many model fields allow you to set a string as the first option for the verbose name of a field. This verbose name is used to create a human-friendly name for the model field. In the case of
update_date, we are setting this name to “Last Updated”.
- And bodytext is a
TextFieldis a large text object that can hold many thousands of characters. As with update date we’re setting the verbose name. In this case we’re setting it to “Page Content”. The final option—
blank=True—is set so that we can create a page without any content. The default for this option is
False, so if you didn’t add any page content, Django will throw an error.
We have only covered a few field types and options in our first model. If you want to have a go creating models now with different field types and options, there are reference tables for common field types and options in the Appendix of Build your first website with Django 2.
There is one more thing we have to do with our model—for a model to be accessible from the admin, it needs to be registered. Registering and configuring a model for the admin is done by adding code to the app’s
admin.py file. Pause the video and enter this text into your code editor or copy it from your transcript.
We have added two lines of code to our
- On Line 2. We import the
- and on Line 4. We register the
Pagemodel with the admin
Very simple. Now we need to create a migration for the
pages app, so Django can add the model to the database. Return to your virtual environment command prompt (exit the development server if it’s still running) and enter:
(env_mfdw)... \mfdw_root >python manage.py makemigrations pages
Then we need to perform the migration. At the command prompt type:
(env_mfdw) ...\mfdw_root>python manage.py migrate
If this doesn’t work and Django complains that it can’t find your
pages app, this is almost certainly because you forgot to add the
pages app to your
INSTALLED_APPS in Module 4.
And we are done. Now it’s time to move on to the admin so we can add some content to our pages.
A First Look at the Django Admin
For most modern websites, an administrative interface (or admin for short) is an essential part of the infrastructure. This is a web-based interface, limited to trusted site administrators, that enables an admin to add, edit and delete site content.
Django comes with a built-in admin—with Django’s admin you can authenticate users, display and handle forms and validate input; all automatically. Django also provides a convenient interface to our models, which is what we will use now to add content to our pages app.
Using the Admin Site
When you ran
startproject in Module 2, Django created and configured the default admin site for you. All that you need to do now is create an admin superuser, to log into the admin site. To create the superuser, run the following command from inside your virtual environment:
python manage.py createsuperuser
Enter your desired username and press enter.
Then You’ll then be prompted for your email address.
The final step is to enter your password. You’ll be asked to enter your password twice, the second time as a confirmation of the first.
Because I’m only doing this video as a demonstration I’m using a very simple password. Django’s security doesn’t like this and will give you a warning if you’re using a password that is too common. As I am sure you already know never use basic passwords in production. Ever.
Now that you have created the superuser, you’re ready to start using the Django admin. Let’s start the development server and explore. Open your web browser to
http://127.0.0.1:8000/admin/. You should see the admin’s login screen.
Log in with the superuser account you created. Once logged in, you should see the Django admin index page.
At the top of the index page is the Authentication and Authorization group with two types of editable content: Groups and Users. They’re provided by the authentication framework included in Django.
Beneath the Authentication and Authorization group is a group added by the admin for our
Page model. We’ll be using this group to add some page content to our site, so go ahead and click the Add link next to the green cross on the right of the
The admin site is designed to be used by non-technical users, and as such it should be self-explanatory. Nevertheless, let’s cover a few of the basic features.
Each type of data in the Django admin site has a change list and an edit form.
Change lists show you all available objects in the database, and edit forms let you add, change or delete records.
We opened the edit form for the
Pages model when we clicked on the add link.
As you’re adding a record, the edit form is blank, allowing you to enter new information into the database. Fill out the fields as follows:
- Title: Meandco Home
- Permalink: /
- Last Updated: Enter any date and time
- Page Content: Enter some content
When entering the page content, remember that it needs to be HTML to display well in your browser. At this stage, a heading and a few paragraphs is OK.
If you need help with HTML, the HTML tutorial on W3schools is a great resource.
Also note that our edit form is using the Last Updated and Page Content verbose field names we entered when we created the
Now that you’ve entered the information for your home page, click the Save and add another button down the bottom right of your screen. Now we’re going to add two more pages to our website first the About Us page — set the Permalink to
/about, set the last updated date to now, and then add some page content. I’m just entering a simple paragraph saying this is the About Us page.
Click save and add another and add the services page. This time the Permalink needs to be
/services. Set the last updated date to now again and add some page content.
Once you have entered the information for your services page, click SAVE rather than Save and add another. This will take you to the Pages change list. The Pages change list can also be accessed from the admin index page by clicking Pages on the left of the group, or by clicking the second Pages link in the breadcrumbs on the top right of the edit page.
Notice that, while the change list contains three page entries, they are named (unhelpfully) “Page object”. This is because we haven’t told the admin what to call our
This is an easy fix. Let’s go back to our
models.py file and make some changes. Pause the video and copy the changes from the screen or copy from your transcript.
So, what did we do here? In lines 9 and 10, we’ve created a new class method. The
__str__ method is a special method that returns a human- readable version of the
Pages class whenever Python asks for a string representation of the Pages object (which is what the admin is doing). If a class doesn’t have a
__str__ method, Python returns the object type—which is why we see “Page object” in the admin change list.
In our modified
models.py, we are simply returning the page title. Refresh the admin screen and you should see a somewhat more useful change list for our pages.
There’s one final thing we want to do with the Pages list display.
While we now have the page titles listed, there is still some work to do to make the list display more useful:
- First, we want an easy way to see when each page was last updated to keep track of changes to our site;
- We also want to display the page titles in alphabetical order to make them easier to browse;
- And we want a handy way to search for a page for when our page count gets larger.
In Django, these changes are very easy to do—you simply add a new class to your
admin.py file. Pause the video and copy the changes from the screen or copy from your transcript.
Let’s step through the new
- Line 4. The
PageAdminclass inherits from Django’s ModelAdmin class.
- Line 5.
list_displaytells Django’s admin what model fields to show in the table columns of the Pages list. Here we’re setting
list_displayto a tuple containing the
- Line 6. The
orderingtuple tells Django’s admin which field to use to sort the list. Note that as the tuple only has a single element, it must have a comma on the end.
- Line 7. The
search_fieldstuple tells Django’s admin which fields should be searched when using the search bar in the model admin. Like ordering,
search_fieldsis a singleton, so don’t forget the comma!
- And finally in line 9, we registered the new
PageAdminclass with the admin.
If you refresh your browser you’ll see the changes to your pages admin:
- You can see that the list has a new column displaying the Last Updated date for each page;
- The pages are now listed in alphabetical order;
- And a new search bar has been added, which allows the user to search for a page using the title field.