Django MVC 패턴


Django 도 MVC (Model View Controller) 의 패턴을 따른다.


Model : models.py
View : template (index.html)

Controller : views.py

 

동작 순서는 다음과 같다.

 

mysite/urls.py로 가서 해당 urlpattern 본다. 

우리는 여기서 http://localhost:8000/polls를 호출 했으니, 

 

mysite/urls.py

from django.contrib import admin
from django.urls import path , include

urlpatterns = [
    path('polls/' , include('polls.urls')),
    path('admin/', admin.site.urls),
]

 

해당 url을 따라서 polls/urls.py를 따라간다.

 

polls/urls.py

from django.urls import path

from . import views
app_name = 'polls'
urlpatterns =[
  path('', views.IndexView.as_view(), name='index'),
  path('/', views.DetailView.as_view(), name='detail'),
  path('/results/', views.ResultsView.as_view(), name='results'),
  path('/vote/', views.vote, name='vote'),
 ]

 

여기에서 http://locahost:8000/polls 를 호출했으니 indexView를 따라간다.

 

polls/views.py

class IndexView(generic.ListView):
  template_name = 'polls/index.html'
  context_object_name = 'latest_question_list'

  def get_queryset(self):
    """Return the last five published questions."""
    return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
  model = Question
  template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
  model = Question
  template_name = 'polls/results.html'


def vote(request, question_id):
  question = get_object_or_404(Question, pk=question_id)
  try:
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
  except (KeyError, Choice.DoesNotExist):

    return render(request, 'polls/detail.html', {
      'question': question,
      'error_message': "You didn't select a choice.",
    })
  else:
    selected_choice.votes += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

 

여기서 index.html을 호출 해서 화면을 보여준다.

 

polls/templates/polls/index.html

 

{% if latest_question_list %}
<ul>
          {% for question in latest_question_list %}
<li><a href ={% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
          {% endfor %}

</ul>

{% else %}

No polls are available.


{% endif %}

 

이런식으로 구동되고,

위에 붙인 소스가 주요 코드이다.

 

 

 

ㅎㅎ mvc 패턴은 생각보다 익숙하지만

python 문법이나 django 모두 생소해서

어려운 부분이 많은것 같다..

그리고 python은 주로 backend로 난 이용할것 같은데.. front보다는

그부분에 대해서 어떻게 구현할지를 더 고민해보아야겠다..

 

그리고 깊이를 익히기 위해선 책을 한권 빌려서 보는게 빠를것 같다 

튜토리얼은 그래도 한번 가볍게 따라하기 좋은것 같다 역시

 

 


참고

https://docs.djangoproject.com/ko/3.0/intro/tutorial03/

 

첫 번째 장고 앱 작성하기, part 3 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

이글은 Django의 튜토리얼을 개인적으로 따라서 해본 글이다

그러고 개인적으로 정리하고자 한다 '-'

 

 


 

1. Django 란?

파이썬 웹 서버 프레임워크이다.

 

가장 특징적인건 ORM (Object Relational Mapping)을 지원한다는 점이다.

ORM은 DB와 데이터 모델 클래스를 연결해준다.

 

그리고 자동으로 관리자화면을 구성해준다..

이부분은 튜토리얼을 따라해보면서 봤는데 신기했다 ㅎㅎ 그리고 꽤 편리해서

잘 이용하면 유용할것 같다란 생각을 했다.

 

 

 

2. Python , Django 설치하기

 

https://www.python.org/downloads/

 

여기서 맞는 os를 선택해서 window일경우 bit도 보고,,

나는 window 64bit라

 

Windows x86-64 executable installer

를 선택해서 설치해 주었다

 

설치할 때 주의 사항은

Path 추가하기를 체크를 꼭 해야한다,, 

 

그이후 cmd 창에서 다음 명령어를 쳐서 설치가 잘 되었는지 확인해준다.

>>python --version

Python 3.7.7

이게 안됐을경우 환경변수를 확인해보자..!

 

 

이제 Django를 설치해주자 proxy가 없는 환경이라면, --proxy 를 빼고 설치해주면된다.

(django만 설치해줘도된다..)

>>pip install --proxy http://proxy_id:proxy_port pylint
>>pip install --proxy http://proxy_id:proxy_port django
>>pipi nstall --proxy http://proxy_id:proxy_port djangorestframework

 

설치가 잘 됐는지, Django 버전도 확인해보자

 

>> python -m django --version

3.0.4

 

 

3. Django 프로젝트 만들기

cmd 창에서 프로젝트를 만들고 싶은 경로에 다음 명령어를 쳐준다.

>>django-admin startproject mysite

 

여기서 mysite는 프로젝트명이다. 그럼 프로젝트가 만들어지고 

 

 

경로에 다음과 같은 파일이 생성 되어있을 것이다.

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

 

그리고 만든 프로젝트를 구동해보자

>> python manage.py runserver

 

 

ㅎㅎ 이번편은 여기까지하고 다음번에 

Django 프로젝트를 구현해보고자 한다.

 

 

 

 


참고

https://docs.djangoproject.com/ko/3.0/intro/tutorial01/

 

첫 번째 장고 앱 작성하기, part 1 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

+ Recent posts