9. How to start writing a new application in Django
Firstly – set up the virtual environment
1. Go to CMD and navigate to Documents. Create a new folder called firstapp and CD into that directory.
2. Create a new virtual environment here, and then run it:
$ python -m venv env $ env\Scripts\activate
The prompt returns (env) when this is done.
3. We now need to install Django in the virtual environment. This will take a minute or so.
$ pip install django
4. Now we can start the actual Django project. To do this we can start the project and give it a name, eg newapp. Type
$ django-admin startproject newapp
5. We can now open VSC and File/Open Folder to open this folder.
Under newapp there is a folder called newapp and in here we can see a few .py files. We can also see manage.py outside this folder too.
6. Back to CMD, cd newapp and you will see manage.py.
We need to create an app within the project. To do this:
$ python manage.py startapp showinfo
We can now start the webserver:
$ python manage.py runserver
If we now go to http://127.0.0.1:8000/ in the browser we can see the install has worked. Note it says:
"You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs."
For now, we can stop the webserver and start building the new application.
1. Set up the models file
Navigate in VSC to firstapp/newapp/showinfo.
Open up models.py to make a class which creates a database table.
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) address = models.CharField(max_length=50) town = models.CharField(max_length=30)
2. Set up URL routing
When users make a request we have to know how to map requests to code. We do this using the URL routing that Django provides.
Navigate in VSC to firstapp/newapp/newapp.
Open up urls.py
Make two changes to the default:
- import “include” from django.urls (2nd line, add include, before import)
- map to a new file called showinfo.urls which we are going to create. So add the whole path line with this in, see belo
We should now have this:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('showinfo.urls')), path('admin/', admin.site.urls), ]
Now I need to navigate back to firstapp/newapp/showinfo and add a new file called urls.py
In this file type this:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
By doing this we are making a promise that there is some function in the views file called index. So we also need to go to the views.py file in this directory and add this code:
from django.shortcuts import render from .models import * def index(request): response_data = Person.objects.all()[0] return render(request, 'showinfo/index.html', {'data':response_data})
This imports all the classes from the models file, and then creates that function we need called index, looks up the data we require and serves it to a template called showinfo/index.html.
3. Creating the template
We need to create this index.html inside a new showinfo directory inside the templates directory, which both need to be created! So in (the first) showinfo create templates and then create showinfo (again) and then index.html.
Here’s a very simple templating example:
<html> <head></head> <body> <p>{{ data.first_name }}</p> </body> </html>
The {{ }} shows we are using Django’s template language. data is the response_data we queried, and first_name one of the database fields.
4. Include the application
Now we need our project to include our application. We’ve written the application that the project doesn’t know it exists yet.
Navigate to firstapp/newapp/newapp (this is the configuration directory) and open up settings.py.
In INSTALLED_APPS we need to add:
'showinfo.apps.ShowinfoConfig',
and save all files so far!
5. Create some data
models.py describes a database table that doesn’t yet exist. It seems like I need to do this step nearer the start, but the app needs to exist in settings.py (the last step). Don’t forget to save that file!
In CMD make sure I am in firstapp/newapp (the directory with manage.py) and do this:
$ python manage.py makemigrations showinfo
This will return something like:
$ showinfo\migrations\0001_initial.py $ - Create model Person
That doesn’t mean it’s in the database. To change the database we need to run the migrations:
$ python manage.py migrate
This executes a whole load of code and should say OK.
We now need to populate the database. Go to newapp/showinfo and create a file called initial.json
I’ve set this up with a new record:
[ { "model": "showinfo.Person", "pk": 1, "fields": { "first_name": "John", "last_name": "Smith", "address": "123 Fake Street", "town": "Springfield" } } ]
(save all!) Back to CMD and type:
$ python manage.py loaddata showinfo/initial.json
This returned:
$ Installed 1 object(s) from 1 fixture(s)
6. See if it works!
Go back to CMD and
$ python manage.py runserver
Then navigate to 127.0.0.1:8000 and we should see a page with a single word on it, John!
Our empty string has been mapped to the function we want; the function has looked up the database, got the string at the database, sent it to the template, and then inserted it into the template.
We could change our template now to give better info. So let’s say we use this:
<html> <head></head> <body> <p>Records in database:<br /> Name: {{ data.first_name }} {{ data.last_name }}<br /> Address: {{ data.address }}, {{ data.town }}<br /><br /> </p> </body> </html>
This would then serve a page that says:
Records in database:
Name: John Smith
Address: 123 Fake Street, Springfield
10. Adding more data
Adjust the views file so it doesn’t just return the first record:
def index(request): response_data = Person.objects.all() return render(request, 'showinfo/index.html', {'data':response_data})
You can adjust the json file to show another record:
[ { "model": "showinfo.Person", "pk": 1, "fields": { "first_name": "John", "last_name": "Smith", "address": "123 Fake Street", "town": "Springfield" } }, { "model": "showinfo.Person", "pk": 2, "fields": { "first_name": "Jane", "last_name": "Jones", "address": "45 Madeup Road", "town": "Langley Falls" } } ]
Don’t forget to add it to the database!
$ python manage.py loaddata showinfo/initial.json
This show return:
$ Installed 2 object(s) from 1 fixture(s)
Then change the template file to read this:
<html> <head></head> <body> <p>Records in database:<br /><br /> {% for x in data %} Name: {{ x.first_name }} {{ x.last_name }}<br /> Address: {{ x.address }}, {{ x.town }}<br /><br /> {% endfor %} </p> </body> </html>
This will return all records.
Wednesday 20 October 2021, 600 views
Next post: 10. Introduction to PostgreSQL Previous post: 8. Building a lightweight project
Advanced Web Development index
- 38. Writing API tests
- 37. Testing in Django
- 36. Class-based views in the Django REST framework
- 35. Building a RESTful web service in Django
- 34. Introduction to CRUD, REST and APIs
- 33. Refactoring with generic views in Django
- 32. Django validators
- 31. Django forms (2) – using the ModelForm class
- 30. Django forms (1)
- 29. JavaScript basics
- 28. Adding CSS to the template
- 27. Django templating
- 26. Deleting and updating records
- 25. Joins, filters and chaining commands
- 24. Using the ORM in views.py
- 23. Adding to the database by writing a script
- 22. Adding to the database with Django Admin
- 21. Migrations
- 20. ORM – work through example
- 19. An introduction to the Object-Relational Mapper
- 18. Altering the database
- 17. SQL functions and summaries
- 16. SQL Query performance
- 15. Queries and table joins in SQL
- 14. Inserts and queries in SQL
- 13. Good practice in relational database design
- 12. Limitations to database modelling
- 11. Building a database using SQL
- 10. Introduction to PostgreSQL
- 9. How to start writing a new application in Django
- 8. Building a lightweight project
- 7. Django URLs
- 6. Django templates
- 5. Django models
- 4. Django views
- 3. Creating a new hello app
- 2. Creating a new virtual environment
- 1. Setting up Django
Leave a Reply