안녕 어떻게 지내? 저는 18세의 백엔드 개발자이자 머신 러닝 엔지니어 지망생입니다. 그리고 이 기사에서는 Python 😁을 사용하여 휴대전화에서 웹 앱을 빌드하는 방법에 대해 쓸 것입니다. 자세히 살펴보겠습니다.

요구사항
여기서 가장 먼저 필요한 것은 안드로이드 폰(적어도 버전 6.0 이상)입니다. 하지만 그것이 우리에게 필요한 전부라고 말하면 어떨까요? 사실이라고 하기에는 너무 좋은 것 같습니다.
이제 우리가 해야 할 다음 일은 pydroid3라는 휴대폰에 모바일 애플리케이션을 설치하는 것입니다.

보시다시피, pydroid3은 휴대전화에서 Python을 작성할 수 있는 모바일 애플리케이션이므로 계속해서 설치하세요.
다음으로 해야 할 일은 Django를 설치하는 것입니다. Django에 익숙하지 않다면 여기에서 Django 문서를 확인하세요.
Django를 설치하려면 pydroid3에서 측면 탐색을 열고 Terminal:
을 선택해야 합니다.
그런 다음 클릭하면 다음과 같이 표시됩니다.

완료되면 다음 명령을 입력하기만 하면 됩니다.
pip install django
그리고 아래를 얻어야 합니다. 이미 설치했기 때문에 "요구 사항 충족" 메시지가 나타납니다.

성공적으로 설치되었지만 확인해 보겠습니다. 터미널 유형 django-admin
에서 Enter 키를 누릅니다.
당신은 이것을 얻어야 합니다:

이는 실제로 이미 설치되어 있음을 의미합니다.
프로젝트 구축 방법
이제 프로젝트 구축을 시작해 보겠습니다. 터미널을 열고 다음 명령을 입력하십시오.
django-admin startproject myapp
그러면 루트 폴더에 myapp이라는 Django 애플리케이션이 생성됩니다.
cd myapp
을 입력하여 디렉토리를 변경하십시오. python manage.py runserver
입력 . 그러면 다음을 얻을 수 있습니다.

이제 서버가 시작되었습니다. 다음으로 브라우저에서 테스트하려면 127.0.0.1:8000을 방문하세요.

그리고 붐! Django가 성공적으로 설정되었음을 알 수 있습니다.
다음으로 해야 할 일은 Django 앱을 만드는 것입니다. Django에서 프로젝트 폴더는 루트 역할을 하고 앱은 애플리케이션 자체 역할을 합니다.
Django 앱을 만들려면 아직 디렉터리에 있는지 확인한 다음 python manage.py startapp todo
를 입력하세요. . 이렇게 하면 myapp 프로젝트에 다음과 같이 할 일 앱이 생성됩니다.

그런 다음 todo 폴더 안에 다음과 같은 내용이 표시되어야 합니다.

작업을 시작할 때 파일을 자세히 살펴보겠습니다.
애플리케이션 구성 방법
이제 Django 프로젝트에서 앱을 제공할 수 있도록 합시다. 우선 settings.py
를 엽니다. myapp 폴더에 파일을 추가하고 'todo'
을 추가합니다. 다음과 같이 설치된 앱에:

다음으로 urls.py
을 열어야 합니다. 코드에 다음을 추가하세요.
from django.urls import path, include
path('', include('todo.urls'))

실제로 일어난 일은 include
를 추가한 것입니다. django.urls
에서 가져오기 경로. 그리고 경로 아래(admin
), urls.py
을 가리키거나 포함하는 빈 경로를 만들었습니다. 할 일 앱 디렉토리에 있는 파일. 그것이 분명하기를 바랍니다.
다음으로 urls.py
라는 이름의 todo 파일 디렉토리에 새 파일을 생성해야 합니다. 다음 코드를 추가하세요.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home')
]

path
를 가져왔습니다. Django.urls
에서 또한 가져온 views
루트 디렉토리에서. 그런 다음 urlpatterns
첫 번째 부분을 루트 링크로 사용합니다. 보시다시피 views.index는 이 뷰가 views.py
의 인덱스 함수를 가리키고 있음을 의미합니다. 파일. 이것이 어떻게 작동하는지 곧 알게 될 것입니다.
views.py
파일을 만들고 코드를 추가하세요.
상단에서 HttpResponse
가져오기 이렇게:
from django.http import HttpResponse
그리고 그 아래에 이것을 추가하십시오:
def index(request):
return HttpResponse('Hello')

보시다시피 urls.py
에서 호출한 인덱스 함수를 만들었습니다. 요청 매개변수를 전달했습니다. 그런 다음 HttpResponse
을 반환했습니다. .
그러나 HttpResponse
전에 작동하려면 django.http import HttpResponse
에서 가져와야 합니다. – ABC처럼 간단합니다. 다음을 시도해 보겠습니다. 터미널을 열고 myapp에 cd하고 python manage.py runserver
를 입력합니다. 테스트합니다.

보시다시피 응답을 반환했습니다. 이제 템플릿 HTML 파일을 로드합니다.
HTML 파일을 로드하려면 다음과 같은 순서로 todo 디렉토리에 폴더를 만들어야 합니다.
todo/templates/todo
todo 디렉토리에 템플릿이라는 폴더를 만듭니다. 그 폴더 안에 todo라는 폴더를 만드는 것처럼 간단합니다.
그런 다음 index.html이라는 간단한 HTML 파일을 만들고 다음과 같이 작성합니다.
<h1>Hello world</h1>
로드하려면 views.py
코드는 다음과 같습니다.
def index(request):
return render(request, 'todo/index.html')

이제 응답을 반환하는 대신 이제 HTML 템플릿을 렌더링할 수 있는 렌더 보기를 반환하고 터미널 cd를 myapp에 저장하고 실행합니다. 우리는 이것을 가지고 있어야합니다

보시다시피 잘 작동합니다. 다음 단계로 넘어갑니다.
정적 파일 설정 방법
이제 정적 파일을 설정하려면 todo 디렉토리에 새 폴더를 만들고 이름을 static으로 지정합니다. 해당 폴더 안에 폴더를 만들고 이름을 todo로 지정합니다.
따라서 다음과 같아야 합니다. /static/todo/
.
todo 디렉토리에서 파일을 만들고 이름을 main.css
로 지정합니다. . 그런 다음 약간의 스타일을 작성해 보겠습니다.
body {
background-color: red;
}
그리고 저장하세요.
이제 index.html
을 다시 편집해 보겠습니다. 다음 코드를 작성하여 파일:
{% load static %}
<!Doctype html>
<html>
<head>
<title>My page</title>
<link rel="stylesheet" href="{% static 'todo/main.css' %}" >
</head>
<body>
Hello
</body>
</html>

이제 실행해 보겠습니다.

저와 함께 따라오셨다면 위의 내용이 있어야 합니다.
모델 및 관리자 패널을 로드하는 방법
이제 관리자 패널을 로드하려면 수퍼유저를 만들어야 합니다. 이것은 간단합니다. 터미널을 열고 myapp 폴더로 이동한 다음 python manage.py createsuperuser
을 입력하기만 하면 됩니다. 그리고 엔터를 치세요. 다음 내용이 표시되어야 합니다.

python manage.py migrate
을 실행하지 않았기 때문에 오류가 발생합니다. 아직. 입력하고 Enter 키를 누르면 다음과 같이 표시됩니다.

이제 python manage.py createsuperuser
를 입력하세요. Enter 키를 누릅니다.

자격 증명을 입력하면 됩니다. 다음으로 해야 할 일은 서버를 실행하고 127.0.0.1:8000/admin을 가리키는 것입니다.

로그인하면 대시보드로 이동합니다:

이제 관리자 패널을 완료했으므로 모델(데이터베이스)로 작업해 보겠습니다. 콘텐츠를 수집하는 모델을 만들겠습니다. 따라서 models.py
를 엽니다. 파일을 작성하고 이 코드를 입력하십시오:
class Post(models.Model):
content = models.CharField(max_length=255, null=False)
def __str__(self):
return self.content

models.Model
매개변수가 있는 클래스를 만듭니다. 변수 content
제공 CharField()
, 텍스트 필드와 비슷합니다. 마지막으로 마법의 str
을 만듭니다. 개체 대신 모델의 이름을 반환합니다.
다음으로 마이그레이션을 실행해야 합니다. 터미널을 열고 myapp에 cd한 다음 python manage.py makemigrations
를 입력합니다. . 다음 내용이 표시되어야 합니다.

이는 데이터베이스에 Post 테이블을 생성했음을 의미합니다. 그런 다음 python manage.py migrate
도 실행하십시오. 결과는 다음과 같습니다.

이것은 모든 것이 분명하다는 것을 의미합니다. 이제 관리자 페이지에 추가하려면 admin.py
를 엽니다. 다음 코드를 입력하세요:
from .models import *
admin.site.register(Post)

모델에서 모든 모델 클래스를 가져오고 관리자 패널에 게시 모델을 등록했습니다. 이제 관리자 패널을 열면 게시물이 표시되고 일부 데이터가 저장됩니다.

이제 할 일 앱 목록에 있습니다.

클릭하면 다음과 같이 표시됩니다.

그런 다음 원하는 경우 게시물을 작성할 수 있습니다.
DB에서 View로 데이터를 렌더링하는 방법
마지막으로 DB에서 데이터를 가져옵니다. 그렇게 하려면 views.py
를 업데이트해야 합니다. 다음과 같이:
from .models import *
def index(request):
content = Post.objects.all()
context = {'content': content}
return render(request, 'todo/index.html', context)

간단합니다. models.py
에서 모두 가져왔습니다. , content
라는 변수를 만들었습니다. , Post 테이블에서 모든 데이터를 검색했습니다. 그런 다음 우리는 그것을 사전으로 우리 보기에 전달했습니다. 따라서 index.html에 다음을 추가하면 됩니다.
{% for contents in content %}
{{content.content}}
{% endfor %}

여기에서는 템플릿 태그를 사용하여 루프를 작성하고 모든 데이터 콘텐츠를 가져왔습니다. 이제 터미널을 열고 myapp으로 cd한 다음 서버를 실행하여 마술이 일어나는지 확인하십시오.

작동하지만 작동하는지 확인하겠습니다.

결과는 다음과 같아야 합니다.

비올라 – 잘 작동합니다. 마지막으로 줄 바꿈을 추가하면 더 명확하게 읽을 수 있습니다. 이제 끝입니다!
읽어 주셔서 감사합니다. Django에 대한 심층적인 자습서를 보려면 내 YouTube 채널 Devstack을 방문하여 구독하세요.