[Django] Python Django 파이썬 장고
pluralsight Python Django Getting Started Lecture Note
파이썬 장고를 옛날에 한번 해봤엇는데 , 다 까먹은것같다.
지금 프로젝트를 하고있는데, 처음에 그냥 html page를 만들어서 보여주기만하기로했었는데, 교수님이 그안에 사람들의 답을 저장해서
나중에 쓸일이있다고하시니, 백앤드까지 다 필요할것같다.
그중에 제일 쉽고 빠르고 편리한 장고를 골라와봤다.
아마도 현재 진행하는 프로젝트는 Django 에 Heroku에 postgress 와함께 배포할예정인데, 시간안에 다할수있을지 모르겠다.
일단 그래서 필요한 장고 lecture부터 찾아보기로했다.
app.pluralsight.com/library/courses/django-getting-started/table-of-contents
수업은 meeting planner를 실습으로 만들면서 이루어진다.
기본적인 djnago 수업이라 model - template - view 에 관한
Django: Getting Started by Reindert-Jan Ekker
Lecture1: Course Overview
Lecture2: Starting a Django Project
Django : Python web frame work
Django: Getting Started
### 2Django: Sratrgin a Django proejct ###
Python Basic of HTML Django : Python web framework
ORM/Admin : powerful tools Template ,URL mapping, Forms , packages
python3 -m venv venv(virtual enviroment directory name) : create virtual enviroment
source venv(virtual enviroment directory name )/bin/activate
pip install django
django-admin startproject meeting_planner : start project and create folder "meeting_planner"
cd meeting_planner
python mange.py runserver
--------------------------------------------------------------------
db.sqlite3 : db data base
__init__.py : empty/ ?
settings.py: where is the proejct is define / setting for the project
urls.py: assignes url
asgi.py , wsgi.py : deployment to the production server
manage.py :
--------------------------------------------------------------------
Lecture3: Creating a simple Web page
create app ?
go to the project folder (meeting_planner)
python manage.py startapp app_name // you can make an app
=> once you create the app you want to build , delte admin.py, apps.py, models.py, tests.py (delete the migrataion file too)
and go back to the main settings.py and add the app in the INSTALLED_APPa
first of all you have to make views.py
from django.http import HttpResponse
def welcome(request):
return HttpResponse("What sup this is skyler's django first page")
and urls.py : you need to import the views and the function and map the url
from website.views import welcome
path('welcome.html', welcome)
path('', welcome) // empty url for the main page
1. make view function
2. import the function in the urls.py
3. url mapping
4. setting add the app
in the production make sure you turn off the debug true
Django App : Python packages
1 web may consisted with mulitple apps
Lecture4: Setting up d Data Model
Django model classes
2core concepts : 1. models (python clases) mapped to database table
2. Migrations (python scripts) keep db structure in sync with code
Migration
python manage.py showmigrations ## show the migration needed
python manage.py migrate ## migrate the thing and if you go to db.squlite3 its automaticlly updtated
GO to model
and write the class
class Meeting(models.Model):
title = models.CharField(max_length=200)
date = models.DateField()
after this you can
python manage.py makemigrations ## to genearate meetings/migrations/0001_initial.py file
python manage.py migrate
you can also change around in the admin page
you need to go to admin.py
and improt what you need to do .
from .models import Meeting
admin.site.register(Meeting)
## to make the super user in admin
python.magage.py createsuperuser email/pwd
Django Models ; saving python objects in a database
Models classesare mapped to tables
fields are mapped to clumns
SQL is generated -
for more django model fields - google
what if you want to add "ROOM " in the model ?
you add the Class Room in the model
To make things easy , you delete all the migratoin file + db.sqlite3 for the clean start
but this makes you have to create the super user ide again
*this is not good idea for the exisiting proejct that has lots data only recommend for the starting the new project
so after delete you have to migrations
python manage.py makemigrations
python manage.py migrate
Lecture5: Combining Model, View, and Template
1)
Model , Template , View
Template - creating webpate / generate HTML
from django.shortcuts import render ##from vidw.py we have to import render
dedef welcome(request):
return render(request, "website/welcome.html") ## return the html page!
now you cna render the html page via rendr from view.py
2) taking parameters from the URL
you need to build the view.py of that certain app with parameter in URL
in this case meetings -> tempalte -> meetings -> details.html
from django.shortcuts import render, get_object_or_404
from .models import Meeting
and the view.py of the meeting will be like this
def detail(request, id):
meeting = get_object_or_404(Meeting, pk=id)
return render(request, "meetings/details.html", {"meeting": meeting})
URL mapping with parameter :
path('meetings/<int:id>', detail),
Lecture6: Urls and Link Building
### 6 Urls and Link Building ####
Link building : Named URL && for loop in template
this let print all the meeting from the database by loop
<ul>
{% for meeting in meetings%}
<li>
<a href="{% url 'detail' meeting.id %}">
<a href="/meetings/{{meeting.id}}"> this is old way
{{meeting.title}}
</a>
</li>
{% endfor%}
</ul>
path('meetings/<int:id>', detail, name="detail") ## this let the naming the URL
3 steps :
-view
-template
-url mapping
make sure you do step by step + you should know what you are doing. (very important)
1. if you want to list all the room in the welcome => add return value in the views.py from home app
2. change view.py in the meeting app
3. change template of both welcome & room deatil .html
4. url mapping
URL mapping
Lecture7: Templates, Styling and Static Contents
CSS stylesheet
make static > website # in the folder in the appropriate postiion
and in the html page put this instead of hard coding the href
{% load static %}
<link rel="stylesheet" href="{% static 'website/style.css' %}" />
img :
<img src= "{% static 'website/1.png' %}" width = "400px">
tempalte inheritance
base.html in right under templates folder
Lecture8: Adding User interaction with ModelFroms
Add ModelForm
Form template
ModelForm
View
in the views.py :
from django.shortcuts import redirect
def new(request):
if request.method == "POST":
form = MeetingForm(request.POST)
if form.is_valid():
form.save()
return redirect("home")
else:
form = MeetingForm()
return render(request, "meetings/new.html", {"form": form})
urls:
path('new', views.new, name="new"),
template:
{% extends "base.html" %} {% block sweetpotato %} {% block potato %} New Meeting
Form {%endblock%}
<h1>Plan a new meeting</h1>
<form method="post">
<table>
{{form}}
</table>
{% csrf_token%}
<button type="submit">Create</button>
</form>
{% endblock%}
마무리 :
이번 강의를 통해서 기본적인 장고 실습을 할수있엇다. 강의내에서 실습예제로 미팅 플래너를 만들었는데, 새 미팅 추가 및 삭제 그리고 미팅룸 설정 까지 할수있는 기본적인 웹사이트를 만들었다. 강의만 따라해도 정말 쉽게 장고에대해서 기본적인 세팅 방법등을 알수있어서 좋은 강의인것같다. 특히 Jane-Ekker강사님의 강의 방식이 정말 쉽고 이해가 잘되게 설명을 해줘서 좋은 강의인것같다. 장고를 처음 공부하는 나한테 딱 맞는 강의였다.
'IT > Web Programming' 카테고리의 다른 글
[ 토크부트] 토크부트(talkbout) 부트캠퍼들의 커뮤니티 (0) | 2021.08.28 |
---|---|
[ 토크부트] 부트캠퍼들의 속시원한 이야기 토크부트(talkbout) (0) | 2021.08.27 |
[Nomadecoder] Vanilla JS , CSS Challenge Day 7 &8/14 (0) | 2021.02.19 |
[Nomadecoder] Vanilla JS , CSS Challenge Day 6/14 (0) | 2021.01.18 |
[Nomadecoder] Vanilla JS , CSS Challenge Day 5/14 (0) | 2021.01.16 |