> For the complete documentation index, see [llms.txt](https://s761111.gitbook.io/raspi-sensor/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://s761111.gitbook.io/raspi-sensor/shi-yong-vs-code-duan-django.md).

# 使用VS Code遠端開發Django

## 一、簡單安裝與測試

由於樹莓派本身的效能並不像一般個人電腦般強大，所以無法在上頭安裝重量級的Python開發工具，比如PyCharm，再加上它並不是標準的Linux X86系統，而是Arm系統，許多重量級開發工具也無法安裝，因此如果可以在個人電腦上安裝重量級的開發工具，利用遠端連線的方式，來編寫樹莓派的Django網站程式，如此就可以保有強大開發工具的效能，也可以很方便的開發樹莓派的Django網站程式，可謂一舉二得，同時這種遠端連線的技巧也可以運用在開發其它的樹莓派Python GPIO程式上。

這次使用的工具是Visual studio code這套由微軟所開發的程式開發工具，由於功能強大且可自由下載使用，因此在這一二年來開始被眾多開發者採用作為開發工具。

官方網站：<https://code.visualstudio.com/>

遠端開發說明網（參考用）：<https://code.visualstudio.com/docs/remote/ssh>

開發Django說明網：<https://code.visualstudio.com/docs/python/tutorial-django>

{% embed url="<https://youtu.be/l9YA6hKZlyo>" %}

## 二、Django 顯示DHT11的溫溼度

利用Django的HttpResponse可以很方便的把簡單的文字（或數字）訊息，透過網頁方式顯示出來，先前學習過的DHT11的技巧與程式碼，可以直接應用在這裡，因為Django核心就是Python語言。這次的程式碼很簡短，但卻是學習Django利用urls.py連結執行函數的最基本觀念與使用技巧。

{% embed url="<https://youtu.be/euvbIpzdvz0>" %}

```python
# 目錄/檔名：gpio/urls.py
from django.urls import path
from .views import dht11

urlpatterns = [
    path('dht11/', dht11),
]
```

```python
# 目錄/檔名：gpio/views.py
from django.shortcuts import render
from django.http import HttpResponse
import Adafruit_DHT

def dht11(request):
    sensor = Adafruit_DHT.DHT11
    pin = 17
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    temp = '溫度：{:.1f}, 溼度：{:.1f}'.format(temperature, humidity)
    return HttpResponse('<h1>' + temp + '</h1>')
```

## 三、透過Django Form表單控制LED燈亮暗

Django提供了非常方便的Form表單製作，可以輕鬆的產生標準的HTML Form表單程式碼，當送到前端後可以利用此表單取得使用者資料輸入值，當使用者把資料傳入後端，從後端取出資料，並且依據使用者的需求打開LED，達到透過網頁控制GPIO的目的，未來可依據此觀念與技巧，實作出強大的物聯網應用程式。

{% embed url="<https://youtu.be/9WV3FIA3yYk>" %}

```python
# gpio/views.py
from django.shortcuts import render
from django.http import HttpResponse
import Adafruit_DHT
from .models import LedForm
import RPi.GPIO as GPIO

def dht11(request):
    sensor = Adafruit_DHT.DHT11
    pin = 17
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    temp = '溫度：{:.1f}, 溼度：{:.1f}'.format(temperature, humidity)
    return HttpResponse('<h1>' + temp + '</h1>')

def led(request):
    if request.method == 'POST':
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(17, GPIO.OUT)
        GPIO.setup(27, GPIO.OUT)
        GPIO.setup(22, GPIO.OUT)
        ledform = LedForm(request.POST)
        if ledform['red'].value() == '1':
            GPIO.output(17, GPIO.HIGH)
        else:
            GPIO.output(17, GPIO.LOW)

        if ledform['yellow'].value() == '1':
            GPIO.output(27, GPIO.HIGH)
        else:
            GPIO.output(27, GPIO.LOW)

        if ledform['green'].value() == '1':
            GPIO.output(22, GPIO.HIGH)
        else:
            GPIO.output(22, GPIO.LOW)

        return render(request, 'gpio/led.html', {'form': ledform})
    ledform = LedForm()
    return render(request, 'gpio/led.html', {'form': ledform})
```

```python
# gpio/models.py
from django.db import models
from django import forms

class LedForm(forms.Form):
    CHOICES = (
        (1, '開'),
        (0, '關'),
    )
    red = forms.BooleanField(label='紅色開關',
                             widget=forms.RadioSelect(choices=CHOICES),
                             initial=0,
                             required=False
                             )
    yellow = forms.BooleanField(label='黃色開關',
                             widget=forms.RadioSelect(choices=CHOICES),
                             initial=0,
                             required=False
                             )
    green = forms.BooleanField(label='綠色開關',
                             widget=forms.RadioSelect(choices=CHOICES),
                             initial=0,
                             required=False
                             )
```

```markup
<!-- templates/gpio/led.html -->
<!DOCTYPE html>
<html lang="zh-Hant-TW">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">送出</button>
</form>
</body>
</html>
```

```python
# gpio/url.py
from django.urls import path
from .views import dht11, led

urlpatterns = [
    path('dht11/', dht11),
    path('led/', led), 
]
```
