Chih-Wei, Hsu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Django Tutorial 1 tags: django, web slideOptions: transition: 'slide' --- # Django Tutorial 1 ### Speaker: Chih-Wei, Hsu ![](https://media-exp1.licdn.com/dms/image/C5103AQEOsP3dI7-KYw/profile-displayphoto-shrink_400_400/0?e=1602720000&v=beta&t=1ZgKSUY7ZCazSqIa-oQDw7fUyHTvIzSX2yYa6oeRsy4 =200x) [About me](https://www.linkedin.com/in/kevin12686/) --- # Frontend ? # Backend ? ---- ```sequence User->Frontend: Read Article Frontend-->Backend: Get Data Note right of Frontend: Getting Data Backend-->Frontend: Give Data Frontend->User: Reading Article ``` ---- ## Getting Data ? ![](https://i.imgur.com/WQJcZ6O.png) ---- ![](https://i.imgur.com/0XIUHTA.jpg =500x) # Request Methods * GET * POST * etc. ---- ## GET Arguments Passed with URL <font color="SkyBlue">Dcard Search Function</font> [https://www.dcard.tw/search<span><!-- .element: class="fragment highlight-red" -->?query=成功大學</span>](https://www.dcard.tw/search?query=成功大學) ---- ## POST Arguments Go with request :warning: <font color="#EAC117">Hided behind, not safe!</font> --- # HTTP Status Code ---- | Code | Meanning | |:----:|:---------------------:| | 200 | Success | | 3xx | Redirect | | 400 | Bad Request | | 403 | Forbidden | | 404 | Not Found | | 405 | Method Not Allowed | | 500 | Internal Server Error | [Details](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Status) ---- 2xx :+1: 4xx :no_entry: 5xx :middle_finger: --- # Prepare [Python 3](https://www.python.org/downloads/) ---- ## Work With Github Create a new repository ---- ## Create Virtual Environment `python -m venv <name>` ---- ## Activate `cd venv/Scripts` `activate` ---- ## Deactivate `deactivate` ---- ## Install Django `pip install django` ---- ## Requirements `pip freeze > requirements.txt` ---- ## Install Requirements `pip install -r requirements.txt` ---- ## Add .gitignore \_\_pycache\_\_/ venv/ migrations/ *.sqlite3 ---- ## Create project `django-admin startproject <name>` ---- ``` django_tutorial │ .gitignore │ requirements.txt ├───backend │ │ manage.py │ └───backend │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py └───venv ``` ---- ## Run `python manage.py runserver` ```shell Performing system checks... System check identified no issues (0 silenced). August 10, 2020 - 10:24:48 Django version 3.1, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ``` ---- [http://127.0.0.1:8000/](http://127.0.0.1:8000/) ![](https://i.imgur.com/BQASIiN.png) ---- ## Git push ![](https://i.imgur.com/6YWji5r.gif) [Check Point 1](https://github.com/kevin12686/django_tutorial/tree/94ae7d7970de8f553613e0ac74bb217ee2a61d11) --- # Django [More](https://www.djangoproject.com/) ---- ![](https://i.imgur.com/VRnirij.png =500x) [Source](https://djangogirlstaipei.gitbooks.io/django-girls-taipei-tutorial/content/django/introduction.html) --- # Simple Blog ---- ## settings.py Configuration of the Django installation ### Modify ```python LANGUAGE_CODE = 'zh-Hant' # Modify TIME_ZONE = 'Asia/Taipei' # Modify ``` [Details](https://docs.djangoproject.com/en/3.1/topics/settings/) ---- ## Create app The name of this example will be 'blog' `python manage.py startapp <name>` ---- ## blog/views.py ### Add ```python from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the blog index.") ``` ---- ## backend/urls.py ### Modify ```python from django.urls import path, include ``` ### Add ```python urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), # Add ] ``` ---- ## blog/urls.py ### Add ```python from django.urls import path from .views import index urlpatterns = [ path('', index, name='Index'), ] ``` ---- [http://127.0.0.1:8000/](http://127.0.0.1:8000/) ![](https://i.imgur.com/96E6fGS.png) ---- ## Git push ![image alt](https://media.giphy.com/media/FGgG4QQF7WkSs/giphy.gif) [Check Point 2](https://github.com/kevin12686/django_tutorial/tree/ae4cd292584801bd0b993ac3d08b394ef5edd500) --- # Models What fields are the blog needed ---- * Title * Content * EditTime ---- ## Data Type ## & ## Restriction ---- * Title * Unique and less than 50 words * Content * Unlimit length * EditTime * Date and Time ---- ## blog/models.py ### Add ```python class Blog(models.Model): title = models.CharField(unique=True, max_length=50, verbose_name='Title') content = models.TextField(verbose_name='Content') editTime = models.DateTimeField(auto_now=True, verbose_name='Edit Time') ``` [More about fields](https://docs.djangoproject.com/en/3.1/ref/models/fields/) ---- ## backend/settings.py ### Add ```python INSTALLED_APPS = [ 'blog.apps.BlogConfig', # Add ... ] ``` ---- ## Make migrations `python manage.py makemigrations <app>` ---- ```shell Migrations for 'blog': blog\migrations\0001_initial.py - Create model Blog ``` ---- ## Migrate `python manage.py migrate` ---- ```shell Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying blog.0001_initial... OK Applying sessions.0001_initial... OK ``` --- # Django Admin Provide a easy way to manage contents ---- ## blog/admin.py ### Add ```python from django.contrib import admin from .models import Blog # Add admin.site.register(Blog) # Add ``` ---- [http://127.0.0.1:8000/admin/](http://127.0.0.1:8000/admin/) ![](https://i.imgur.com/h4fqMWL.png) ---- ## Create Superuser `python manage.py createsuperuser` ---- ```shell Username: admin Email address: Password: **** Password (again): **** Superuser created successfully. ``` ---- ## Login ![](https://i.imgur.com/u6474gD.png) ---- ## Git push ![image alt](https://media.giphy.com/media/yXBqba0Zx8S4/giphy.gif) [Check Point 3](https://github.com/kevin12686/django_tutorial/tree/55ba9bb3fdfdfd0499bd5e6c0053aa39c5aa8839) --- # Exercise Create a website for selling products * Require model * Product * Fields * Name * Description * Quantity * etc. --- # Listing ---- ## Templates Create a folder 'templates' under 'blog' ---- ## backend/settings.py ### Modify ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path.joinpath(BASE_DIR, 'blog', 'templates'), ], # Modify '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', ], }, }, ] ``` ---- ## blog/views.py ### Modify ```python from django.shortcuts import render # Add from .models import Blog # Add def index(request): blogs = Blog.objects.all() # Modify return render(request, 'index.html', {'blogs': blogs}) # Modify ``` ---- ## bolg/templates/index.html ### Add ```htmlembedded <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Blog</title> </head> <body> <ul> {% for blog in blogs %} <li>{{ blog.title }}</li> {% endfor %} </ul> </body> </html> ``` ---- [http://127.0.0.1:8000/](http://127.0.0.1:8000/) ![](https://i.imgur.com/uju2lO1.png) ---- ## Git push ![image alt](https://media.giphy.com/media/kEKcOWl8RMLde/giphy.gif) [Check Point 4](https://github.com/kevin12686/django_tutorial/tree/2137085da2f6b234ca2db7917a77885cec12d522) --- # RESTful API Each request methods have their own meaning ---- | Method | Meaning | |:------:|:-------:| | GET | Read | | POST | Create | | PUT | Update | | DELETE | Delete | ---- # Json Javascript Object Notation ---- `{}` descripts an object with key and value `[]` represents as an array --- # Rest Framework [More](https://www.django-rest-framework.org/) ---- ## Install `pip install djangorestframework` ---- ## Update requiremnets `pip freeze > requirements.txt` ---- ## backend/settings.py ### Add ```python INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'rest_framework', # Add ] ``` ---- ## blog/serializers.py ### Add ```python from rest_framework.serializers import ModelSerializer from .models import Blog class BlogSerializer(ModelSerializer): class Meta: model = Blog fields = '__all__' ``` ---- ## blog/views.py ### Add ```python from rest_framework.viewsets import ModelViewSet from .serializers import BlogSerializer class BlogViewSet(ModelViewSet): serializer_class = BlogSerializer queryset = Blog.objects.all() ``` ---- ## blog/urls.py ### Modify ```python from django.urls import path, include # Modify from rest_framework.routers import DefaultRouter # Add from .views import index, BlogViewSet # Modify router = DefaultRouter() # Add router.register('blog', BlogViewSet) # Add urlpatterns = [ path('', index, name='Index'), path('api/', include(router.urls)), # Add ] ``` ---- [http://127.0.0.1:8000/api/](http://127.0.0.1:8000/api/) ![](https://i.imgur.com/6oMPVKI.png) ---- [http://127.0.0.1:8000/api/blog/](http://127.0.0.1:8000/api/blog/) ![](https://i.imgur.com/qMohAZk.png) ---- [http://127.0.0.1:8000/api/blog/?format=json](http://127.0.0.1:8000/api/blog/?format=json) ```json [ { "id":1, "title":"blog1", "content":"hello this is blog 1", "editTime":"2020-08-11T09:35:50.677858+08:00" }, { "id":2, "title":"blog 2", "content":"hello this is blog 2", "editTime":"2020-08-11T09:36:01.424723+08:00" }, { "id":3, "title":"blog 3", "content":"hello this is blog 3", "editTime":"2020-08-11T09:36:11.285941+08:00" } ] ``` ---- ## Git push ![](https://i.imgur.com/3foXgyU.gif) [Check Point 5](https://github.com/kevin12686/django_tutorial/tree/c56acc0302eae507ad5176d1283c969aaef81d80) --- # Exercise List products with a page and an api Give list page some styles --- ![](https://i.imgur.com/w83QWDE.png =300x) [Github](https://github.com/kevin12686/django_tutorial) --- <!-- .slide: data-background="https://i.imgur.com/VrcGp6z.png" -->

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully