[web sever 구축_파이선_DJANGO #1]Django로 웹 사이트 구축하기
web sever 구축_파이선 장고로 웹 사이트 구축하기
===================================================================
[ 장고 설치하기]
- 파이선 웹프로그램 : 파이선의 패키중에 웹 프로그래밍 전문 패키지임
[hello 출력하기]
[ elections data db에 저장하기]
[ elections data db에 data 추가하기]
[ DATA 보여주기]
[아나콘다 prompt에서 manage.py 실행하기]
[탬플릿으로 html 불러오기]
[탬플릿에 정보채우기]
[여론조사 모델]
[ url 다루기]
[ 여론조사 화면 구현]
[ 여론조사 결과를 DB에 저장 ]
[ 참고자료 ]
==>https://programmers.co.kr/learn/courses/6
==================================================================
[ 장고 설치하기]
아나콘다 콘솔화면에서 ==> pip install django django-admin startproject <프로젝트이름> => 프로젝트 이름은 mysite 로 한다 python manage.py runserver ==> 서버가 실행이 됨 웹브로우저 실행하여 접속함: http://127.0.0.1:8000/
서버가 실행중이면, 콘솔로 다른 작업이 불가능함, 콘솔에서 ctrl+c 로 종료를 해주어야 다른 작업이 가능해짐
[hello 출력하기] python manage.py startapp <앱이름> ==> 앱 이름은 elections 로 한다 views.py 작성: 자동으로 생성된 views.py를 아래 내용으로 수정한다 from django.shortcuts import render from django.http import HttpResponse def index(request):r return HttpResponse("Hello world") mysite 내의 urls.py 수정 ==> 웹 실행시 실행될 app 지정 urlpatterns = [ url(r'^', include('elections.urls')), ==> http://127.0.0.1:8000 으로 접속했을때, elections.urls을 실행하라고 지정해주는 것이다
==> include실행을 위해서는 mysite내의 urls.py 내에서 from django.conf.urls import include를 선언해주어야 함 url(r'^admin/', admin.site.urls),
==> admin으로 접속했을때, admin 화면으로 접속하게된다 ] elections 폴더에 urls.py 화일 작성 ==> http://127.0.0.1:8000/ 접속시 view.py내의 index 함수를 실행하라고 지정을 해줌
=> 그러면 최종적으로는 view.index 화일이 실행이 됨 from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ]
[ elections data db에 저장하기] models.py 수정==> class Candidate(models.Model): ==> 후보자 data 정의 name=models.CharField(max_length=10) introduction=models.TextField() area=models.CharField(max_length=15) party_number=models.IntegerField(default=1) db에 models.py의 data를 저장한다=> 시스템 off시 화일이 없어지지 않고, 저장케 하는 방법은 db에 저장하는것이다. mysite 내의 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'elections' ==> 추가해 준다 ] mysite 에서 python manage.py makemigrations 실행
==>model data를 db에 어떤형식으로 쓸것인가에 대해 정의함
==> db 항목의 변화가 있때마다 실행을 해줘야 반영이 됨 python manage.py migrate ==> 실제로 db를 만들어줌, ==> db 항목의 변화가 있때마다 실행을 해줘야 반영이 됨
[ elections data db에 data 추가하기] >python manage.py createsuperuser name : david 비밀번호 2번 입력 : a1a1a1aa1 >python manage.py reunserver 웹브러우저에서 127.0.0.1:8000/admin admin.py 화일 수정 from django.contrib import admin # Register your models here. from .models import Candidate ==> models.py화일에서 Candidate를 불러다 쓰겠다는 내용임 admin.site.register(Candidate) Candidate가 추가되었음을 볼수있음.
data 추가를 하면 candidate object로 구분이 되지 않음. 이를 해결하기 위해, model.py화일에 name으로 식별하겠다고 정의해줌 def __str__(self): ==> def 뒤에 한칸을 띄고, 줄마춤을 맞추어야 한다. return self.name
![]()
[ DATA 보여주기] view.py 수정하기 def index(request): candidates = Candidate.objects.all() str = "" for candidate in candidates: str += "<p>{}기호 {}번 ({})<BR>".format(candidate.name, candidate.party_number, candidate.area) str += candidate.introduction + "</P>" return HttpResponse(str)
[아나콘다 prompt에서 manage.py 실행하기]
>python manage.py shell 이후 나타는 [1]. [2] 라인에 코딩을 하면, 실행이 됨 [1]from elections.models import Candidate [2] new_candidate = Candidate(name = "홍명순") [3]new_candidate.save()
[4]Candidate.objects.all()[5] no1 = Candidate.objects.filter(party_number = 1)[6] no1[0].party_number[7] no1[0].name
[탬플릿으로 html 불러오기]
템플릿 추가하기 templates 폴더 생성 (\mysite\elections\templates) elecetions 폴더 생성(\mysite\elections\templates\elections) index.html 파일 생성 (\mysite\elections\templates\elections\index.html)
index.html 화일 수정하기
<!DOCTYPE html> <html lang="en"> <head> <title>선거 후보</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <td><B>이름</B></td> <td><B>소개</B></td> <td><B>출마지역</B></td> <td><B>기호</B></td> </tr> </thead> <tbody> <tr> <td>가후보</td> <td>후보입니다.</td> <td>우리나라</td> <td>기호1번</td> </tr> <tr> <td>나후보</td> <td>후보입니다.</td> <td>우리나라</td> <td>기호2번</td> </tr> <tbody> </table> </body>
VIEW.PY 화일 수정
from django.shortcuts import render from django.http import HttpResponse from .models import Candidate def index(request): candidates = Candidate.objects.all() return render(request,'elections/index.html')
[탬플릿에 정보채우기]
cadidate의 내용을 cpntext 매개로해서, html에 전달함
views.py 화일 수정
def index(request):
candidates = Candidate.objects.all()
context={'candidates':candidates} ==>사전만들기
return render(request,'elections/index.html',context)
index.html 화일 수정 ==> 데이터를 동적으로 받아 출력함
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<td><B>이름</B></td>
<td><B>소개</B></td>
<td><B>출마지역</B></td>
<td><B>기호</B></td>
</tr>
</thead>
<tbody>
{% for candidate in candidates %}
<tr>
<td>{{candidate.name}}</td>
<td>{{candidate.introduction}}</td>
<td>{{candidate.area}}</td>
<td>기호{{candidate.party_number}}번</td>
</tr>
{% endfor %}
<tbody>
</table>
</body>
[여론조사 모델]
model.py 화일 수정
class Poll(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
area = models.CharField(max_length = 15)
class Choice(models.Model):
poll = models.ForeignKey(Poll) #Poll 모델의 id를 이용
candidate = models.ForeignKey(Candidate)
votes = models.IntegerField(default = 0)
admin.py 화일 수정
from django.contrib import admin
# Register your models here.
from .models import Candidate,Poll ==> poll 추가
admin.site.register(Candidate)
admin.site.register(Poll) ==> poll 추가등록
[ url 다루기]
index 화일 수정
<td> {{candidate.area}} </td>
==> <td> <a href = "areas/{{candidate.area}}/">{{candidate.area}}</a> </td>
urs.py 화일 수정
url(r'^areas/(?P<area>.+)/$', views.areas)
views.py 화일 수정
def areas(request, area) :
return HttpResponse(area)
[ 여론조사 화면 구현]
area.html 화일 작성
<!DOCTYPE html>
<html lang="en">
<head>
<title>지역구</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>지역구</h1>
<br>
<table class="table table-striped">
<thead>
<tr>
<td><B>이름</B></td>
<td><B>소개</B></td>
<td><B>기호</B></td>
<td><B>지지하기</B></td>
</tr>
</thead>
<tbody>
<tr>
<td> 후보1</td>
<td> 후보소개 </td>
<td> 기호1번 </td>
<td>
<form action = "#" method="post">
<button name="choice" value="#">선택</button>
</form>
</td>
</tr>
<tr>
<td> 후보2</td>
<td> 후보소개 </td>
<td> 기호2번 </td>
<td>
<form action = "#" method="post">
<button name="choice" value="#">선택</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</body>
view.py file 수정
def areas(request, area):
candidates = Candidate.objects.filter(area = area) #Candidate의 area와 매개변수 area가 같은 객체만 불러오기
context = {'candidates': candidates,
'area' : area}
return render(request, 'elections/area.html', context)
area.html 화일 수정
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{area}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>{{area}}</h1>
<br>
<table class="table table-striped">
<thead>
<tr>
<td><B>이름</B></td>
<td><B>소개</B></td>
<td><B>기호</B></td>
<td><B>지지하기</B></td>
</tr>
</thead>
<tbody>
{% for candidate in candidates %}
<tr>
<td> {{candidate.name}}</td>
<td> {{candidate.introduction}}</td>
<td> 기호{{candidate.party_number}}번 </td>
<td>
<form action = "#" method = "post">
<button name="choice" value="#">선택</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
area에 현재 진행 중인 poll이 있는지 확인하기
views.py 화일 수정
from .models import Candidate, Poll, Choice import datetime
area.html 화일 수정
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{area}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>{{area}}</h1>
<br>
{% if poll %}
<table class="table table-striped">
<thead>
<tr>
<td><B>이름</B></td>
<td><B>소개</B></td>
<td><B>기호</B></td>
<td><B>지지하기</B></td>
</tr>
</thead>
<tbody>
{% for candidate in candidates %}
<tr>
<td> {{candidate.name}}</td>
<td> {{candidate.introduction}}</td>
<td> 기호{{candidate.party_number}}번 </td>
<td>
<form action = "#" method = "post">
<button name="choice" value="#">선택</button>
</form>
</td>
</tr>
{% endfor %}
<tbody>
</table>
{% else %}
여론조사가 없습니다
{% endif %}
</div>
</body>
[ 여론조사 결과를 DB에 저장 ]
웹사이트에서 결과를 전달
<!-- C:\Code\mysite\templates\elections\area.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{area}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>지역구</h1>
<br>
{% if poll %}
<table class="table table-striped">
<thead>
<tr>
<td><B>이름</B></td>
<td><B>소개</B></td>
<td><B>기호</B></td>
<td><B>지지하기</B></td>
</tr>
</thead>
<tbody>
{% for candidate in candidates %}
<tr>
<td> {{candidate.name}}</td>
<td> {{candidate.introduction}}</td>
<td> 기호{{candidate.party_number}}번 </td>
<td>
<form action = "/polls/{{poll.id}}/" method = "post">
{% csrf_token %}
<button name="choice" value="{{candidate.id}}">선택</button>
</form>
</td>
</tr>
{% endfor %}
<tbody>
</table>
{% else %}
여론조사가 없습니다
{% endif %}
</div>
</body>
action에서 지정한 url을 등록
코드추가
urlpatterns = [
# 기존 url 유지
url(r'^polls/(?P<poll_id>\d+)/$', views.polls)
]
view.polls 구현 => views.py 수정
코드추가
def polls(request, poll_id):
poll = Poll.objects.get(pk = poll_id)
selection = request.POST['choice']
try:
choice = Choice.objects.get(poll_id = poll.id, candidate_id = selection)
choice.votes += 1
choice.save()
except:
choice = Choice(poll_id = poll.id, candidate_id = selection, votes = 1)
choice.save()
return HttpResponse("finish")
[ 참고자료 ]
'프로젝트 > Web Server 구축' 카테고리의 다른 글
[web sever 구축_파이선_DJANGO #3 ] Django WEB 배포하기 (0) | 2017.09.11 |
---|---|
[web sever 구축_파이선_DJANGO #2 ] 버전/백업관리를 위한 GIT 활용 (0) | 2017.09.11 |
IOT(사물인터넷) 웹 서비스 구축하기( github에 웹서버 적용) #5 (0) | 2017.07.23 |
IOT(사물인터넷) 웹 서비스 구축하기(WordPress 적용) #4 (0) | 2017.06.18 |
Cafe24 CDN 서버 활용하기 (0) | 2017.06.17 |
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.
[협동조합 #1] 시장환경분석/postioning
본글은 " MOT_협동조합 Study 모임" 에서 진행중인 협동조합에 관한 글입니다.
"전략이 있는 쇼핑몰 창업계획서 만들기 _ 이은성 지음" 서적을 기초로 창업계획서를 만드는 과정입니다.
글의 순서는 아래와 같습니다.
====================================================================
1. 시장환경분석
2. A Group(모형,교육산업,코딩교구) 시장환경 분석
3. A Group(모형,교육산업,코딩교구) positioning
4. 참고자료
====================================================================
[ 시장환경분석]
[A Group(모형,교육산업,코딩교구) 시장환경 분석]
[A Group(모형,교육산업,코딩교구)_positioning]
'스타트업 > 협동조합' 카테고리의 다른 글
협동조합 비즈니스 전략 (0) | 2017.05.13 |
---|---|
도서 "협동조합 참 좋다 " (0) | 2017.05.09 |