[Django] first try

Django

Create a project

$ django-admin startproject mysite
Project structure will look like this:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Run development server

$ python manage.py runserver 8080
Then open browser and enter localhost:8080

The development server will automatically reloads Python code change. But manual restart is still needed when adding a file or other rare situation.


Create a Polls app

Projects vs. apps
apps are web applications have specified purpose, project is a collections of apps.

$ python manage.py startapp polls

Project structure will look like this:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

Add the first view

  1. Open polls/view.py and add code snippet below
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello world from polls")
  1. After modifying view file, we need let Django knows how to get the view file (map view to a URL)

Create polls/urls.py and add following code:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index')
]

Next step is modifying mysite/urls.py to let the whole project knows how to reach polls app.

  1. Import django.urls.include
  2. Include polls.urls

mysite/urls.py will look like this:

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

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.


Knowledge

path()

path() function has four arguments: route, view, [kwargs], [name]

route:
order for URL matching
For example:

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

When localhost:8080/polls comes, Django will first match the first element in urlpatterns, which is polls/, matches!

When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.

Writing your first Django app, part 1 | Django documentation | Django

HTTP verbs
Patterns don’t search GET and POST parameters, or the domain name.

For example:
https://www.example.com/myapp/
https://www.example.com/myapp/?page=3
Two urls are treated as same, Django will look for myapp/ in URLconf.

view:
When Django finds a matching url, it calls corresponding view with an HTTPRequest object

kwargs: (optional)
Arbitrary keyword arguments can be passed in a dictionary to the target view.

name: (optional)
Give the URL a name to avoid unambiguous naming routes


Connect database

We are using MySQL as our database.
In mysite/settings.py, find DATABASES variable, change default configure to:

    'default' : {
        'ENGINE' : 'django.db.backends.mysql',
        'NAME' : 'mysite',
        'USER' : 'root',
        'PASSWORD' : 'root',
    }

database mysite must exist in MySQL database before making setting change

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容