[TOC]

1. Understanding about Django and react.js

  • Django: MVCT(model, view, control, template) development framework in Python/HTML
  • react.js: organize modules in JavaScript

    2. Two related projects that used Django:

  1. Blog like project - Django for development, AWS for online data storage
    1. Users, posts, profile, user picture, display of posts in Django
    2. save information in AWS, so that profiles can be saved online
  2. Twitter like app - Django for development, react.js for static files
    1. Users, tweets, profile, user picture, display of posts in Django
    2. test some settings in react.js, use “build” and “collectstatic” commands to move them into django

      3. Important Steps in Development Processes (Django)

      1. set up python and django environment

  • This step depends on your current Python version and OS

  • every time we do the test, we run the server by

    python ./manage.py runserver
    

    the default path to access is “localhost:8000”

  • if want to run the server with another port

    python ./manage.py runserver [int between 1-65535]
    

    (to avoid conflict, port should be better >= 1000)

    3. apps

    a. create new apps

    python ./manage.py startapp [app_name]
    

    b. modify /[app_name]/models.py:
    c. sign the new app in /[project_name]/settings.py:

    # ...
    INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
    
      '[app_name]', # new
    ]
    # ...
    

    d. every time when there is a new app or models.py of the new app changed, make migrations and migrate

    python ./manage.py makemigrations
    python ./manage.py migrate
    

    4. store data in apps

    python ./manage.py shell
    >>> from [app_name].models import [app_class_name]
    >>> ...
    
  • for example, we have /tweets/models.py: ```python from django.db import models

class Tweet(models.Model):

# id = models.AutoField(primary_key=True) 
content = models.TextField(blank=True, null=True)
image = models.FileField(upload_to="images/", blank=True, null=True)

# id is the primary key
# blank=True -> not mandatory in django
# null=True -> not mandatory in the database
```bash
(reactjs) [root@localhost Twittme]# ./manage.py shell
Python 3.6.5 (default, Sep 10 2018, 09:39:42) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from tweets.models import Tweet
>>> obj = Tweet()
>>> obj.abc = 123
>>> obj.abc
123
>>> obj.content = "Hello World"
>>> obj.content
'Hello World'
>>> obj.save()
>>> exit()

(reactjs) [root@localhost Twittme]# ./manage.py shell
Python 3.6.5 (default, Sep 10 2018, 09:39:42) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from tweets.models import Tweet
>>> obj = Tweet.objects.get(id=1)
>>> obj.content
'Hello World'
>>> obj.abc
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Tweet' object has no attribute 'abc'
  • we add a “Hello World”in fact, the idea is to treat [app_name] as tables, [app_class_name] as objects in tables, we declare a new object and set it’s actually exist variables, then save to keep it.

    5. urls

    routing
  • for example, create our first view, home_view in /tweets/views.py: ```python from django.http import HttpResponse # new from django.shortcuts import render

def home_view(request, args, *kwargs): # new return HttpResponse(“

Hello World

“)


- for routing, modify /Twittme/urls.py:
```python
from django.contrib import admin
from django.urls import path

from tweets.views import home_view # new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view), # new
]

(Here we also have a default ‘admin/‘ to administrate variables/objects in the project)

dynamic routing
  • to expand, create another view in /tweets/views.py to receive url details: ```python from django.http import HttpResponse from django.shortcuts import render

def home_view(request, args, *kwargs): print(args, kwargs) return HttpResponse(“

Hello World

“)

def tweet_detail_view(request, tweet_id, args, *kwargs): # new print(args, kwargs) return HttpResponse(f”

Hello {tweet_id}

“)


- new route in /Twittme/urls.py:
```python
from django.contrib import admin
from django.urls import path, re_path

from tweets.views import home_view, tweet_detail_view # new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view),
    path('tweets/<int:tweet_id>', tweet_detail_view), # new
]
  • if not found, we also have to handle status such as 404.

    6. templates:

  • create a templates/ folder under Twittme/ under the project directory

  • add the template folder path to /Twittme/settings.py: ```bash

TEMPLATES = [ { ‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,

    # 'DIRS': [],
    'DIRS': [os.path.join(BASE_DIR, "templates")],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]


- Them we can render views to /templates

for example, I have created another directory in /templates called /pages<br />then home.html in /pages
```html
<!--home.html-->
<h1>Hello World</h1>

refer the path in /[app_name]/views.py to the template page before:

# ...
def home_view(request, *args, **kwargs):
    # return HttpResponse("<h1>Hello World</h1>")
    return render(request, "pages/home.html", context={}, status=200)
# ...

7. HTML data dynamic load:

https://www.yuque.com/akiencore/qgdgg5/gu1b5l#DrMqO

  • views.py of apps handle and send data to templates
  • templates load them dynamically
  • also, templates can use