<본 강좌는 Mike Hibbert에 의해 제작되었으며, 제가 정리한 내용이 도움이 된다고 생각되시면 반드시 유투브 페이지에 방문하셔서 추천과 구독을 눌러주세요>

Tutorial4에서는 views.py와 urls.py를 이전 Tutorial에서 정해져 있는 위치가 아니라 각각의 기능에 맞춰 분리하여 별도로 관리하는 방법에 대해서 설명을 한다.

django 프로젝트를 만들면 urls.py는 기본적으로 프로젝트명과 동일한 하위 폴더에 생성이 된다.

 그러나, 이번 Tutorial4에서는 프로젝트 내 생성된 App인 article 내부에 urls.py를 만들고 활용하게 된다.

 

 

 

이렇게 만들었을 때 관건은 결국 django_test/urls.py로 들어온 요청을 어떻게 article/urls.py로 연결하는것인데 생각보단 간단하다.

django_test/urls.py 파일에 r'^articles/'(articles로 들어온 모든 요청을) include('article.urls')(article.urls에서 찾아) 을 추가하면 된다.

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'django_test.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    (r'^articles/', include('article.urls')),
   
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', 'article.views.hello'),
    url(r'^hello_template/$', 'article.views.hello_template'),
    url(r'^hello_template_simple/$', 'article.views.hello_template_simple'),
   
   
)

이렇게 작성해 놓으면 http://127.0.0.1:8888/articles/ 로 접속했을 때, article/urls.py로 이동해서 path를 찾게 된다.

따라서 아래와 같이 article/urls.py에 아래와 같이 작성하면 http://127.0.0.1:8888/articles/all 이라고 할 경우 article/views.py에서 articles라는 함수를 찾게 된다.

 

from django.conf.urls import patterns, include, url

urlpatterns = patterns ('',

        url(r'^all/$', 'article.views.articles'),
        url(r'^get/(?P<article_id>\d+)/$', 'article.views.article'),                       
                       
)      

 

그럼 위에서 연결시킨 것과 같이 article/views.py에 articles 함수와 articles 함수를 추가해보도록 하자.

tutorial 예제에서는 전 장에서 설명한 것과 같이 render_to_response를 통해서 간단한 함수를 제시하였다.

 


from django.template.loader import get_template
from django.template import Context
from django.shortcuts import render_to_response
from article.models import Article


# Create your views here.

def hello(request):
    name = "mike"
    html = "<html><body> Hi %s, this seems to have worked</body></html>" % name
    return HttpResponse(html)

def hello_template(request):
    name = 'mike'
    t = get_template('hello.html')
    html = t.render(Context({'name':name}))
    return HttpResponse(html)

def hello_template_simple(request):
    name = 'mike'
    return render_to_response('hello.html', {'name':name})


def articles(request):
    return render_to_response('articles.html', {'articles':Article.objects.all()})

def article(request, article_id=1):
    return render_to_response('article.html', {'article':Article.objects.get(id=article_id)})

articles 함수에서는 articles.html 파일에 db의 Article Table에 저장되어 있는 모든 내용을 호출하는 기능을 넣었고,

article 함수에서는 article.html 파일에 db의 Article Table에 저장되어 있는 모든 내용 중 id가 article_id와 동일한 데이터를 호출하는 기능을 추가하였다.

이미 알고 있겠지만 Article.objects.all()은 models.py에 class로 정의되어 만들어진 Article Table에 저장되어 있는 모든(all() 데이터를 호출한다는 의미이며, Article.objects.get(id=article_id)는 동일하지만, 모든(all()) 데이터가 아니라 id가 article_id와 동일한 데이터(get(id=article_id)만 호출한다는 의미이다.

 

article.html은 다음과 같이 작성하고,

<html>
 
 <body>
  
  <h1> {{article.title}}</h1>
  <p>{{article.body}}</p>
 
  
 </body>
 
</html>

 

articles.html은 다음과 같이 작성하자.

<html>
 <body>
  
  <h1>Articles</h1>
  {% for article in articles %}
  <div>
   
   <h2><a href="/articles/get/{{article.id}}/">{{article.title}}</a></h2>
   <p>{{article.body}}</p>
   
   
  </div>
  {% endfor %}
 </body>
 
</html>

article.html에 있는 내용은 특별히 설명이 필요 없을 듯 하나, articles.html에는 기존에 없었던 django템플릿 언어가 일부 들어가 있다.

python을 이미 익힌 사람들은 알겠지만 python과 유사하게 django 템플릿에서도 for문을 사용할 수 있는데 다음과 같다.

  • {% for article in articles %} : articles(Articles.objects.all())에 포함되어 있는 내용들을 하나 하나 article이란 이름으로 호출할 것이다.
  • {{ article.title }}: 호출되고 있는  article의 title 콜롬의 데이터를 가져온다.
  • {% endfor %}: for문을 종료 한다.

위 내용은 기존의 python문법과 유사하기 때문에 크게 어려움은 없을 것이라 생각 된다.

모든 작성을 마치고 http://127.0.0.1:8888/articles/all/ 에 접속하면 다음과 같은 화면이 뜰 것이다.

만약 Tutorial을 처음부터 차근차근 해온 사람이라면 Tutorial2에서 models.py에서 Table을 만들고 데이터를 넣는 작업을 했기 때문에 아래와 같이 출력되는 데이터들이 있을 것이나, 만약 블로그의 내용만 보고 따라온 사람들은 아무런 데이터도 나오지 않을 것이다.

이 경우에는 앞에 Tutorial2의 동영상을 참고 부탁 한다.(17분 30초 이후부터 보면 데이터를 cmd창에서 Shell화면을 호출하여 입력하는 강의가 나온다.) 사실 admin에 들어가서 데이터를 직접 입력하는게 더 간단하지만 다음 Tutorial이라 그 장에서 설명하려 한다.

 

 

 

 


 

 

 

+ Recent posts