HomeBack-End & DatabaseDjango Basics – Part2

Django Basics – Part2

In this post we will mainly see about django model and database operations



Let’s first added some fields to model so we can explore different type of fields our model will look like this

task -- varchar 255
description - text
due_date - date
is_complete - boolean
complete_percentage - decimal
created_at - datetime
updated_at - datetime

Here is how the code looks for this

Also i got error when creating migrations to specify default values as well. Make sure run migrate commands to create the relevant database changes


Let’s look into relationship with models. e.g let create new model called “users” and associated “users” with “todo”


here update this code in Todo model when creating a relation between user model and todo model
> user = models.ForeignKey(User, on_delete=models.CASCADE,   db_constraint=False)


Let’s add route for login, registration as well and also add the relevant code to save user

For now i have added empty routes and this is how the code looks


There is a problem with this, which i see. Our routes for “login”, ” register” are like /todo/login and /todo/register which doesn’t look good. Rather it should be like “/auth/login” or “/auth/register” for this we need install another “app” called “user” which will do.

Now our code base looks like this

This is much better, the router is /user/login which makes better sense.

Also after moving everything to “user” app including views, models the code looks like this


There is one important thing in this about dependencies and migrations. Since we have two different apps “user” and “todo” during the migration process we need to mention that “todo” depends on user only then the foreign key can be setup. Read more about it here and its important

Code for login route as well

make sure to go through this route in detail and understand it. there are many new things in the codebase


Next, let’s update our existing to add todo. Since we need to assign to a user now.

But before going further

Right now we are seeing lot of problem with django and rest api to list a few

  1. Django model returns data which is not possible to send back as an json response
  2. There is no default to send back a json response
  3. All routes by default are protected via CSRF which doesn’t make sense for rest api’s

overall we can see that django by default is not suitable for rest api’s but rather very much suited for making a website.

But, based on current tech trends frameworks like angularjs, react, vue are more preferred for frontend and node/python are mainly used a rest api framework.

Hence we need a better framework to manage rest api for that we have

Before going ahead we should switch to rest api framework.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: