In previous blog we saw just basics of django and should have understood basics of apps, routes, model at-least theoretically.
Now, let’s implement the same things for a todo app and do it step by step.
First step is to create a “app” named todo in your existing django application.
$ python3 manage.py startapp todo
This will create a new app called “todo”
Next, lets make a route “index” first will just return “hello world”
https://github.com/pythexcel/django_tutorial/commit/2bc17e104140eb436b0593298629c62e9b74e17b
Reference https://docs.djangoproject.com/en/2.2/intro/tutorial01/
Next, let’s make a simple todo model. For now will we just have
id: primary key
task: text
created_at: Date
P.S. For now the engine is kept to the default sqlite3 only
This the code for the same
https://github.com/pythexcel/django_tutorial/commit/1141aee019ebfdfe64785e727b2dedc5cf8a6f86
Reference
https://docs.djangoproject.com/en/2.2/intro/tutorial02/
Now, let’s add a “POST” route to add a new Todo
https://github.com/pythexcel/django_tutorial/commit/2aca4102f19ea8e380d9f07745b3505908f23f10
Once you have done this and you test our the route in postman you will get a “CSRF” error like this
The reason being, all POST are protected via CSRF. Read more about it here
https://stackoverflow.com/a/4547721
Next, to remove the error do the following
https://github.com/pythexcel/django_tutorial/commit/2c27f56cf53395275b58161e029e60f141aca259
After doing this the api will work
also, in case of a non POST request we should return a proper error response using this
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseBadRequest
https://github.com/pythexcel/django_tutorial/commit/2835d90536145b719e1d62528059032e51dd4fc4
Now if you fire a GET request, you get a proper Error Code 405
Next, let’s actually save some data to db using the route.
P.S. I got an error an error no table defined "todo_todo" to fix i had to run command $ python3 manage.py migrate
https://github.com/pythexcel/django_tutorial/commit/dcda2197476c604a79b7e609504beaf7249e238b
So far so good!
Next, lets add a route to fetch all Todo from our database
Also at this stage we can introduce class based views
https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#handling-forms-with-class-based-views
Basically in this we can easily define get, post routes in a much better code structure. Go through the above link
Updating the code structure with the changes
https://github.com/pythexcel/django_tutorial/commit/14b7a0b791eb838af9e92b12964ea7375dc29a64
Reference https://stackoverflow.com/a/38498887
Go through the above code in detail to understand it.
Now finally to fetch all Todo’s
https://github.com/pythexcel/django_tutorial/commit/2e21b5b6f34592abfbea6a1d69a3967d23f3dd43
Ok, so till now we have had a basic understanding of this. In next posts we will explore more on django model and more database operations.