DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

Python(Django) learning from scratch (Full stack goal)

Hi Friends,
I am Nikhil Roy front-end developer now it's time to dive some new things so new concept new books new entertainment.

In this post, I will learn python(Django) from scratch and update every topic here and discuss about it.

Start Time: 8PM (GMT+6)

Basic tools.

  • Visual Studio Code
  • Git Bash
  • Python 3.8.8 and install all notify extension at vs code.

After we are ready to install everything we will dive to
git Bash and vs terminal to execute the command and install those modules.
For learning purpose, we will use https://www.djangoproject.com/ Official website
and for other issue we will google it and attach those links here.

Let's begin.

First let's see some command, open your git Bash command line

python --version # output: Python 3.8.5

python -m django --version # output: 3.0.8
pip --version # output pip 20.2.2 from c:\python\python38-32\lib\site-packages\pip (python 3.8)


Enter fullscreen mode Exit fullscreen mode

if everything ok then,
pip install django-admin
django-admin startproject full_night_project it will create one new directory "full_night_project"
then,
cd full_night_project
code .
now we will use our Visual studio code terminal to type any command. for open the terminal press "Ctrl+ "
(
mean backquote)
then,
manage.py startapp nightapp
manage.py runserver
then,
open http://127.0.0.1:8000/
and you will see the django template which we are doing to our project.

Writing First View.

open the nightapp > views.py
then, paste this code

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World, hello nightapp")
Enter fullscreen mode Exit fullscreen mode

this is for simple view,
create one file name, urls.py at nightapp
and paste,

from django.urls import path
from .import views

urlpatterns = [
    path('',views.index,name="Homepage")
]
Enter fullscreen mode Exit fullscreen mode

after we have to go full_night_project> urls.py (be sure it's old one which already there)
paste,



from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('nightapp.urls'),name="NightApp")
]

Enter fullscreen mode Exit fullscreen mode

then, reload the server http://127.0.0.1:8000/
you could see output Hello World, hello nightapp
Little glance
path() function has 4 arguments

  • route
  • views
  • kwargs
  • name but 2 is the required route and view, other are optional for more glance 5min to read here. Our basic web app is ready to start working now

Database setup

open up full_night_project > settings.py

for database we will use the MySQL database
the default database is SQLite.

open up the settings.py and replace the the DATABASE like below

DATABASES = {
    "default":{
        "ENGINE": 'django.db.backends.mysql',
        "NAME": "nightapp",
        "USER": "",
        "PASSWORD": "",
        "HOST": '',
        "PORT": ''
    }
}
Enter fullscreen mode Exit fullscreen mode

for security reason, we have to create a user and password ourself.
for more about MySQL we will follow https://www.mysql.com/ Official Documentation there we have to download MySQL

Windows (x86, 64-bit), ZIP Archive
.................. 10 Minute Break...........

It's 8:51 PM

also include the app name at INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'nightapp.apps.NightappConfig'
]

Enter fullscreen mode Exit fullscreen mode

last one the NightappConfig coming from apps.py class name.

After we modify the settings.py then,
paste this command Visual Studio code terminal
manage.py migrate
for the previous command, we can use the arrow up key to get manage.py runserver to run the server.

Creating Model

The model contains essential fields and behavior of the data we are storing.
open up nightapp>models.py

we are creating here 2 model class

*1

from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=2000)
    votes = models.IntegerField(default=0)    
Enter fullscreen mode Exit fullscreen mode

Choice is associate with Question class here.

The field has various types of arguments, the max_length uses for validation and MySQL value also.
after doing this, we have to go to terminal
and,

manage.py makemigrations
Enter fullscreen mode Exit fullscreen mode

the output will show at the terminal like this

 nightapp\migrations\0001_initial.py
    - Create model Question
    - Create model Choice
Enter fullscreen mode Exit fullscreen mode

whenever we change anything on models.py
we have to upgrade it by running manage.py makemigrations
then,

manage.py migrate
Enter fullscreen mode Exit fullscreen mode

so we can see those output also our MySQL database, now it's connected from our MySQL database.
Here, we have learn about this 2 command
manage.py makemigrations and manage.py migrate

......... Reading the documentation........
now we are going different,
so go to terminal and follow the command
manage.py shell
then, paste one by one to see terminal how the shell working.

  • from nightapp.models import Choice, Question `Import the model classes we just wrote.

No questions are in the system yet.`

  • Question.objects.all()
  • from django.utils import timezone
  • q = Question(question_text="What's new?", pub_date=timezone.now())

Save the object into the database. You have to call save() explicitly.

  • q.save() now it has a id
  • q.id Access model field values via Python attributes.
  • q.question_text
  • q.question_text = "What's up?"
  • q.save()
  • Question.objects.all() See, when you use Question.objects.all() you are getting output like but we have to change it different way. An Intance of this way we can open up our models.py and paste like below.
from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")
    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=2000)
    votes = models.IntegerField(default=0)  
    def __str__(self):
        return self.choice_text  
Enter fullscreen mode Exit fullscreen mode

this return self.choice_text is render instance of this one
we have learn some basic concept here by reading the django documentation.

Django Admin

for creating the admin we have to use some command below the command

manage.py createsuperuser

Enter fullscreen mode Exit fullscreen mode

and here we have to create our admin panel username, password, email for admin.

and after we have created the admin panel then we can run the server again and can browse http://127.0.0.1:8000/admin/

there we see Groups and Users.
These things coming from settings django.contrib.auth

for use the Question and choice basically models.py any models.Model we have to register from admin.py
for this, open up admin.py

and paste

from django.contrib import admin

# Register your models here.
from .models import Question
admin.site.register(Question)
Enter fullscreen mode Exit fullscreen mode

after we register the model then we could see a new row at django admin panel.
you can see the Question option has his question after you click Question you can see all the values of Question model classes.
now, we are going to create one more Model for practice,


class Student(models.Model):
    name = models.CharField(max_length=30)
    classRoom = models.IntegerField()
    age = models.IntegerField()
    gender = models.CharField(max_length=10)
    mobile = models.IntegerField()
    email = models.EmailField(max_length=25)
    country = models.CharField(max_length=25)
    description = models.CharField(max_length=150) 
    def __str__(self):
        return self.name     
Enter fullscreen mode Exit fullscreen mode

So, finally we are ready our database, models, admin panel.

It's 11:00 PM

Focusing views

https://docs.djangoproject.com/en/3.1/intro/tutorial03/

urlpatterns testing

urlpatterns = [
    path('<int:id>/',views.index,name="Homepage")
]
Enter fullscreen mode Exit fullscreen mode

how, we are doing template

Template

create a templates folder inside nightapp
and create a fle called index.html to work with this index file.
.......................Thanks all guys, will continue next tutorial tomorrow.........
Good Night.

Top comments (0)