- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Secured Interactions in a Django Meeting Planner
A small consultancy needs an internal tool to stop double-booking its two shared meeting rooms. You are handed a freshly generated Django project and must turn it into a working planner: routes that resolve meetings by ID and fail gracefully when they don't exist, a data model connecting meetings to rooms and attendees, an admin panel that shows the office manager how full each meeting is, browsable list and detail pages styled with the company's CSS, and forms that only logged-in users can use to create a meeting or, after confirming, delete one.
Lab Info
Table of Contents
-
Challenge
Step 1: Orientation to the Meeting Planner platform
The double-booking problem
A small consultancy shares two meeting rooms across every team, and right now the only booking system is a shared spreadsheet that people forget to update. Two teams show up to Room A at the same time, someone books a room that's already full for the afternoon, and nobody can see who is supposed to be in a meeting until they walk in. You have been handed a freshly generated Django project,
meetplanner, and asked to turn it into the office's real booking tool.By the end of this lab the project will resolve meetings by id and fail gracefully when one doesn't exist, store meetings with their room and attendees in a real database, show that data through browsable pages styled with the company's CSS, and let only logged-in users create or delete a meeting. ### Touring the generated project
Inside
meetplanner/you will find the pieces every Django request passes through:views.py—the functions that turn an incoming request into a response.urls.py—the routing table that maps a URL path to a view.models.py—the Python classes that describe the database tables (Meeting,Room,Attendee).admin.py—customization of the built-in admin site the office manager will use.templates/meetplanner/andstatic/meetplanner/—the HTML that renders and the CSS that styles it.
The templates, URL routes, settings, and database configuration are already written so you can focus on the Python that ties them together. Several functions are stubbed with a
# TODOcomment marking exactly where your work goes.The project's dependencies are installed in a ready-made virtual environment,
venv/. Every command in this lab calls its interpreter directly asvenv/bin/python. ### Where you're headedHere's what you'll accomplish in the remaining steps:
- Step 2: Get the server answering requests, view the application in the Web Browser tab, and add a meeting lookup route with a custom 404 response when an ID doesn't exist.
- Step 3: Complete the
Meetingmodel's string representation and query helper, add a field and migrate the database, and display an attendee count in the admin's meeting list. - Step 4: Render the landing, list, and detail pages using a shared base template and static CSS.
- Step 5: Validate the booking form against overlapping room reservations, protect the create and delete flows with a login check, and add a confirmation step that only accepts a
POSTrequest for deletion. - Step 6: Log in and test every feature in the browser.
Each step builds on the work completed in the previous step, so work through them in order.
-
Challenge
Step 2: Stand up the project and route core requests
Answering the first request
Django's development server can already start and serve the project, but
status_view, the view behind/status/inmeetplanner/views.py, is unfinished.A status endpoint like this provides a simple way to verify that routing works from end to end: a request comes in, a view function runs, and a response goes back out. Here, the response uses JSON, a text format programs use to exchange data.
A load balancer or monitoring tool could also check this endpoint to determine whether the service is responding, so it's worth getting right before building anything more elaborate on top of it. ### See the server answer
The check called
status_viewdirectly. Now watch the same view answer a real HTTP request.-
In the Terminal, start the development server:
venv/bin/python main.pymain.pyrunsmanage.py runserver 0.0.0.0:8001 --insecure. The--insecureflag allows the server to serve CSS files even thoughDEBUGisFalse. KeepingDEBUGset toFalsealso ensures the project's custom 404 page is used.At startup, you'll see a warning about unapplied migrations. This is expected because the database tables haven't been created yet. You'll create them in Task 3.3. The server is ready when it prints
Quit the server with CONTROL-C. -
Open the Web Browser tab, enter in the following address and press
Enter.:localhost:8001/status/The tab's default address,
localhost:8000, points to a different service. The page should display the JSON returned by your view:{"status": "ok", "service": "meetplanner"}
The server reloads automatically whenever you save a file, so you can leave it running and return to the browser after completing each task. The lab has one terminal, so press
Control+Cto stop the server whenever you need to run another command. Restart it using the same command. ### Named routes and a graceful 404Django matches an incoming path against
urlpatternsinurls.pyand calls the matching view with any captured values, such as a meeting's id. The lookup route is already declared aspath("lookup/<int:meeting_id>/", views.meeting_lookup, name="meeting_lookup"), and itsnamelets templates and redirects point to it without hard-coding the path. What the view still needs to decide is what happens when the id doesn't match anything. RaisingHttp404hands control to Django's 404 handling, which—becauseDEBUGisFalse—renders the project's owntemplates/404.htmland shows your message instead of a debug page or a server error. ### SummaryWith the server running, try the lookup route in the Web Browser tab. Navigate to
localhost:8001/lookup/2/to seeBudget Review, then openlocalhost:8001/lookup/999/to see the custom 404 page displayingMeeting not found.In this step, you ran the project from its provided virtual environment and followed a request through
urls.pyto a view and back.status_viewreturns JSON, whilemeeting_lookupresolves an ID from the URL or raisesHttp404. Next, you'll replace the hard-codedMEETINGSlist with real database models. -
-
Challenge
Step 3: Model and manage meeting data
Modeling meetings, rooms, and attendees
meetplanner/models.pyalready definesMeeting,Room, andAttendeeas Django models with fields and foreign keys connecting them. A meeting belongs to one room and has many attendees.What's missing is a readable string representation, which Python gets from the model's
__str__method. Without one, admin messages and the Python shell show a generic value such asMeeting object (1), which doesn't identify the meeting or its room. ### A query helper for what's aheadEvery page that lists meetings should show what's coming up, not a growing pile of history. Rather than repeating a filter-and-order query in every view, it belongs once on the model itself as a classmethod (a method you call on the class itself), so
views.pycan callMeeting.upcoming().django.utils.timezone.now()gives the current, timezone-aware moment to compare against. That is the correct way to compare datetimes in Django whenUSE_TZis on, rather than Python's owndatetime.now(). ### Changing the model means migrating the databaseA model class describes a table, but the table itself lives in
db.sqlite3, and Django never changes it just becausemodels.pychanged. Migrations connect the two:makemigrationscompares your models with the migration files already inmeetplanner/migrations/and writes a new file describing the difference. The project ships with0001_initial.py, which creates theRoom,Meeting, andAttendeetables.migrateapplies every migration the database hasn't seen yet and records each one in adjango_migrationstable, so it runs exactly once. The firstmigratealso creates the tables for Django's built-in apps, such as users and sessions.
The office manager wants room for a short agenda on each meeting. Adding it takes one line in the model and two terminal commands. If the server from Step 2 is still running, press
Control+Cin the Terminal first. ### Customizing the admin for daily useDjango's admin site is generated automatically from your models, but the default list view only shows each row's string form.
admin.pyalready registersMeetingAdminwith alist_displaythat includes a column calledattendee_count-- a computed column that tells the office manager how full a meeting is without opening it. For that column, the admin calls theMeetingAdminmethod of the same name with eachMeetingrow in turn. -
Challenge
Step 4: Render meeting list and detail templates
A shared base template and static CSS
meetplanner/templates/meetplanner/base.htmlalready defines the page shell: a navigation bar, a link to the project's static CSS file, and a{% block content %}that every other template fills in.Building pages by extending this base, rather than writing full HTML documents each time, is called template inheritance. Change the navigation once in
base.html, and every page that extends it picks up the change.home_viewis the first view to demonstrate this, renderinghome.html, which extendsbase.html. ### Listing what's upcomingWith
Meeting.upcoming()built in Step 3, the list page's job is to fetch that queryset and pass it to a template.meeting_list.html(which already extendsbase.html) loops over the meetings under the context key"meetings"and links each title to its detail page with{% url 'meeting_detail' meeting.pk %}, using the named route fromurls.py. ### Showing one meeting in fullThe detail page needs a single
Meetinginstance rather than a queryset, and it needs to fail the same way the lookup route did in Step 2 when the ID is wrong.get_object_or_404does both jobs in one call: it fetches the record or raisesHttp404automatically, so the view doesn't need its owntry/exceptaroundMeeting.objects.get(). ### See the pages renderStart the server again if it isn't running (
venv/bin/python main.py). In the Web Browser tab, openlocalhost:8001/.The dark navigation bar and white content card come from
style.css, linked once inbase.html. The page reportsThere are currently 0 upcoming meetings.Choose Meetings in the navigation bar. The list page uses the same layout and shows
No upcoming meetings.because the database is still empty. You'll add meetings through the admin and open their detail pages in Step 6. -
Challenge
Step 5: Secure meeting forms and deletion flow
Validating a booking before it saves
meetplanner/forms.pyalready definesMeetingFormas aModelFormoverMeeting, which gives it fields and per-field validation for free. What it can't check automatically is a rule that spans multiple meetings: two bookings for the same room can't overlap in time. That kind of cross-field, cross-record rule belongs in the form'sclean()method, which Django calls after individual field validation and beforeis_valid()returns its final answer. ### Creating meetings behind a login check@login_requiredis a decorator that wraps a view so Django checks for an authenticated session before the view runs. An anonymous request is redirected toLOGIN_URLinsettings.py,/accounts/login/, whichurls.pyserves with Django's built-in login view.meeting_createis already decorated this way. The remaining work is what happens once a logged-in user submits the form: validating it, saving it, redirecting the user afterward, and showing errors when the form doesn't validate. ### Deleting only on a confirmedPOSTDeleting data is one action in this project that should never happen from a plain link click because a
GETrequest can be triggered accidentally by a prefetch or a bookmark.The safe pattern is to let
GETrender a confirmation page and reserve the actualdelete()call for aPOSTthe user submits deliberately. Combined with the@login_requiredcheck, this ensures that only authenticated users can delete meetings through aPOSTrequest. -
Challenge
Step 6: Run the application
Use the whole planner
Every task is graded, but you haven't yet used the planner the way the office manager will. In this step, you'll create an account, add data through the admin, and use each page you built.
Prepare the database and an account
In the Terminal, press
Control+Cfirst if the server is running. Make sure every migration is applied:venv/bin/python manage.py migrateIf Task 3.3 already applied everything, this prints
No migrations to apply.Then create an administrator account:venv/bin/python manage.py createsuperuserIt asks for a username, an email address (press
Enterto skip it), and a password twice. The password prompt shows nothing as you type. The output ends withSuperuser created successfully.Start the server:
venv/bin/python main.py ``` ### Try each feature in the Web Browser tab Open the **Web Browser** tab and enter the following in the address bar and press `Enter`.localhost:8001
Click the **Open in new tab** icon (↗) on the right side of the address bar to open the application in a separate browser tab. > **Note:** For each check below, return to the Code Lab's **Web Browser** tab, enter the corresponding path after `localhost:8001`, and click **Open in new tab** to open the page in a separate browser tab. Use the separate tab to interact with the application, as the embedded browser may prevent login and other form submissions from working correctly. 1. **Status and lookup (Tasks 2.1, 2.2).** `/status/` shows `{"status": "ok", "service": "meetplanner"}`. `/lookup/2/` shows `Budget Review`, and `/lookup/999/` shows the custom 404 page displaying `Meeting not found`. 2. **Login required (Task 5.2).** Go to `/meetings/create/`. Because you aren't logged in, you're redirected to the **Log in** page, with `?next=/meetings/create/` in the address. Log in with your superuser account, and you're sent to the **New Meeting** form. Its **Room** list is empty, so add rooms next. 3. **Admin (Tasks 3.1, 3.3, 3.4).** Go to `/admin/`. Under **Meetplanner**, add two rooms, such as `Room A` and `Room B`. Then add a meeting in `Room A` that starts tomorrow, give it an agenda, and add two attendees in the rows at the bottom. The confirmation message names the meeting as `<title> (Room A)`, which comes from your `__str__` method. The **Agenda** field is there because of your migration, and the **Meetings** list shows `2` in the **Attendees** column. 4. **Home and list (Tasks 3.2, 4.1, 4.2).** Choose **Home** in the navigation bar. It now reports `1` upcoming meeting. Choose **Meetings** to see it listed with its room and start time. 5. **Detail and 404 (Task 4.3).** Select the meeting's title to open its detail page with the room, times, agenda, and attendees. Then change the address to `/meetings/999/` to see the custom 404 page. 6. **Double-booking (Tasks 5.1, 5.2).** Choose **New Meeting** and book `Room A` for a time that overlaps your first meeting. The form returns with `This room is already booked at that time` and keeps what you entered. Switch the room to `Room B` and save. You should land on the new meeting's detail page. 7. **Confirmed delete (Task 5.3).** On that detail page, choose **Delete this meeting**. The confirmation page appears, and the meeting remains in the list until you choose **Confirm delete**, which returns you to the list without it. 8. **Logged out (Task 5.3).** Choose **Log out** in the navigation bar, then visit `/meetings/1/delete/`. You're redirected to the login page instead of the confirmation page. ### Run the checks yourself The lab ran each task's test as you went, but they are ordinary pytest tests you can run whenever you like. The lab has one terminal, so press `Control+C` to stop the server first. Then run the whole suite: ```bash venv/bin/python -m pytest -qThe last line starts with
12 passed. To run one task's test:bash runTest.sh test_task_2_1Each failure names the task it belongs to, so the output tells you which step to go back to. One thing worth trying before you finish: break something on purpose and watch the corresponding check fail, then restore it. Knowing what a failure looks like is just as valuable as knowing what a passing check looks like.
When you're done, everything you've written remains in the editor tabs, so you can revisit your work.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.