Make a deck of cards with Django
Learn you Django by making a deck of cards out of internets.
For the impatient, source code is here
Start the project
create a virtual environment and activate it
venv is a convention. It creates a new environment for our project where we’ll install django and other packages. A virtual environment is like a virtual machine with way less overhead. Add venv to .gitignore for version control.
Install django and generate a requirements.txt file. This is where all the packages that our app requires will be defined. It’s like a gemfile in ruby or package.json in node.
This creates our project directory. Now we create a new app called cards where we will have all of our application logic.
cards is now an app we’ll use within the django_cards project. In django_cards/settings.py add cards to our installed apps:
Create a card model in cards/models.py. This will define the columns in our
Add to a new file cards/utils.py:
Now we’re going to set up our database. Make the migrations and migrate the database. We’re also going to run the create deck function.
Next we’ll set up routing. In the project directory (django_cards) add a new route:
This regex matches our index route and will use the view as defined in the views.py file of our card app. The last parameter gives our route a name.
Define the home view:
This provides all the card data to our template. Inside of the cards directory add a templates/cards.html. This will be our homepage. Django automatically knows to search for cards.html inside of a templates directory.
Add a basic loop to templates/cards.html:
Then run the server and see the card data displayed on localhost:8000
We’ll make our template a bit more snazzy:
We now use get_FIELD_display to show the suit name. This is a bit magical to me, had to investigate on SO.
In future tutorials we will build up actual functionality to play cards. Keep an eye on the SOURCE code for this tutorial!