sumit
1/3/2020 - 7:17 AM

django

1 Design 2 Database 3. Models 4 Hosting 5 Maintain 6. Marketing 7. Monetizing the app 8. Asking for investments Django: A web framework based on python

1. setup

For Mac: Install homebrew, python3, pipenv(virtual environment creator in python)

  • Use python3
  • pip3 install pipenv
  • Install django with pipenv pipenv install django==2.1 ( this will create a virtual environment with django installed, if it worked correctly Pipfile and Pipfile.lock get created)

Start and Exit virtual environment

pipenv shell
exit

2. Create Project

django-admin startproject project_name .

Without . Django adds an additional directory to the project

manage.py and project_name folder are created

To run django server

python manage.py runserver

Basic Knowledge of Django Project

  • a single project powers a single website
  • a project can contain multiple apps

Apps

  • each app focusses on a particular aspect

Example (a shopping website):

  • one app for user authentication
  • another app for handling payments
  • another app for listing items

3. create a new app

python manage.py startapp hello

--inside app folder
__init__.py admin.py    apps.py     migrations  models.py   tests.py    views.py

--inside project folder
__init__.py asgi.py     settings.py urls.py     wsgi.py

3.0 edit file project_name/settings.py INSTALLED_APPS array and add 'app_name', at the end.

because after above command hello app is created but this django project doesn't know about the app yet, so now

Function-Based Views

Method 1 : create a view for the target url

edit file app_name/views.py file

# Create your views here.
from django.http import HttpResponse

def appView(request):
  return HttpResponse('Hello, World!')

3.2 update urls

update the project_name/urls.py file

from django.contrib import admin
from django.urls import path
from app_name.views import appView as app_nameView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('appwebpath/', app_nameView) 
]

RUN APP from http://127.0.0.1:8000/appwebpath/

3.3 Template

So: Templates, Views, URLs. This pattern will hold true for every Django web page you make. Every web framework needs a convenient way to generate HTML files. In Django, the approach is to use templates so that individual HTML files can be served by a view to a web page specified by the URL.

Run below command alongside manange.py file mkdir templates

cd templates

  • insert the todo.html file inside templates folder,inside templates folder we will keep all of our html files
  • .html files will be called from editing file hello/views.py file
from django.shortcuts import render
from django.http import HttpResponse
 
def appView(request):
  return render(request, 'todo.html')
  • it will still not work because you have todo.html file isn't able to read as it's directory path isn't given. So change the project_name/settings.py file
TEMPLATES = [
    {
        'BACKEND': ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': ...
        'OPTIONS': ...
    },
]

3.4 Models

Models: A way to interact with your database Django sets up SQLite databse by default, so you don't have to do anything

change your APP/model.py file

from django.db import models

# Create your models here.
class ToDoItem(models.Model):
    content = models.TextField()
    # date_created = models.DateTimeField
    # author = models.CharField()

Note that we’ve created a new database model called ToDoItem which has the database field text. We’ve also specified the type of content it will hold, TextField(). Django provides many model fields supporting common types of content such as characters,dates, integers, emails, and so on.

Tell Django to make changes in configuration of Database

python manage.py makemigrations

python manage.py migrate

To interact with APP using terminal python manage.py shell

Database basics

from todo.models import ToDoItem
ToDoItem

# list all rows
all_items = ToDoItem.objects.all()  

# adding new row
a = ToDoItem(content = "permament todo Item 1")
a.save() # saving object to database

# fetch data inside first row
ToDoItem.objects.all()[0].content
ToDoItem.objects.all()[0].id # automatically assigned unique identifier
 
 # fetch data of unique id =1
 ToDoItem.objects.get(id=1)
 
 # deleting first item 
 ToDoItem.objects.all()[0].delete()

Adding Database content in html file change the APP/views.py file

from django.shortcuts import render
from .models import ToDoItem
def toDoView(request):
    all_todo_items = ToDoItem.objects.all()
    return render(request, 'todo.html', 
        {'all_todo_items': all_todo_items})

3rd argument of render functions states the dictionary which contains variables which we can access in html file directly

Access model variable in html file, syntax of for loop below is Django-specific way

<ul>
    {% for todo_item in all_todo_items}
        <li>{{todo_item.content}}</li>
    {% endfor %}
</ul>

Django will't recognise your starting block tag, if you have a space between the { and the %.

Form html

<form action="/addTodo/" method="post">{% csrf_token %}
    <input type="text" name="content" />
    <input type="submit" value="Add" />
</form>
  • csrf_token is added just for security purposes
  • post method if you want to add something in database, get method if you want to fetch something from database
  • the way this works is after clicking Add button post method is send to url BASE URL + /addTodo/ for

Getting data from post request

  • insert function addTodo in APP/views.py
def addTodo(request):
    # create a new todo item and save it
    c = request.POST['content']
    new_item = ToDoItem(content=c)
    new_item.save()

    # redirect the broser to  '/todo/' 
    return HttpResponseRedirect('/todo/')
  • In urls.py add path('addTodo'/, addTodo)

Method 2 : Class-Based Views