티스토리 뷰

Philosophy

Generating admin sites for your staff or clients to add, change and delete content is tedious work that doesn’t require much creativity. For that reason, Django entirely automates creation of admin interfaces for models.

Django was written in a newsroom environment, with a very clear separation between “content publishers” and the “public” site. Site managers use the system to add news stories, events, sports scores, etc., and that content is displayed on the public site. Django solves the problem of creating a unified interface for site administrators to edit content.

The admin isn’t intended to be used by site visitors. It’s for site managers.


*admin user 생성하기

우선 우리는 admin site에 로그인이 가능한 유저를 생성해야한다.(비밀번호는 1234567890 )

$ python manage.py createsuperuser

Username (leave blank to use 'eminentstar'): admin

Email address: pjk3843@gmail.com 

Password: 

Password (again): 

Superuser created successfully.


*개발 서버를 시작하라.
-django admin site는 디폴트로 활성화되었다. 개발 서버를 시작하고 탐험하라.

$ python manage.py runserver

-그리고 http://127.0.0.1:8000/admin 로 접속하라.

그러면 다음과 같은 로그인 화면이 뜰 것이다.

Django admin login screen



*관리자 페이지에 들어가기.

로그인 후 이 화면이 보일 것이다. 이 몇개의 수정가능한 내용은 django.contrib.auth에 의해 제공되는데 장고의 의해 shipped된 the authentication framework다.

Django admin index page


*Make the poll app modifiable in the admin

그러나 우리의 poll app은 볼 수가 없다. 단 한가지를 해보자. 우리는 우리의 admin에게 Question 객체가 admin 인터페이스를 가진다는 걸 말할 필요가 있다. 이것을 하기위해서 polls/admin.py 파일을 열고 수정을 하자.


from django.contrib import admin


from .models import Question


# Register your models here.

admin.site.register(Question)



*자유로운 관리자 기능을 탐험하자.

이제 Question이 등록되었고, Django는 Question항목이 admin index 페이지에 보여야만 한다는 것을 안다.


Django admin index page, now with polls displayed


Questions를 클릭해보자. questions를 위한 'change list'에 있다.



 이 페이지는 디비에 있는 모든 questions를 보여주고 그것을 변경할 수 있게 선택 할 수 있다. 앞서 Part 1에서 생성한 question이 보인다.


클릭을 하면 수정이 가능하다.



주목할 만한게 몇가지 있다.

  • 폼은 Question 모델로 부터 자동적으로 생성된다.
  • The different model field types(DateTimeField, CharField)는 적절한 HTML 입력 위젯과 상응된다.
  • 각각의 DateTimeField는 자바스크립트 shortcuts을 얻는다. ex) Today, Now
페이지의 하단은 관리자에게 몇가지 옵션을 준다.
  • Save: 변화를 저장하고 change-list 페이지를 반환한다. 
  • Save and continue editing: 변화를 저장하고, 이 객체에 대한 관리자 페이지를 reload한다.
  • Save and add another: 변화를 저장하고 새로운 이 객체에 대한 텅빈 폼을 load한다.
  • Delete: 삭제 Confirmation 페이지를 보여준다.
History를 누르면 수정내역을 볼 수 있다.

*Customize the admin form

admin.site.register(Question)를 Question 모델과 함께 등록함으로써, Django는 default form representation을 설계할 수 있다.장고에게 몇가지 등록 사항을 말함으로써 우리는 admin form을 custromize 할 수 있다. polls/admin.py의 admin.site.register(Question) 라인을 대체 해보자.

from django.contrib import admin


from .models import Question


# Register your models here.

class QuestionAdmin(admin.ModelAdmin):

  fields = ['pub_date','question_text']

admin.site.register(Question, QuestionAdmin)


이 패턴을 따를 것인데, model admin 객체를 생성하고, 그것을 register메소드의 두번째 매개변수로 넘겨야 한다.

from django.contrib import admin


from .models import Question


# Register your models here.

class QuestionAdmin(admin.ModelAdmin):

  fieldsets = [

    (None,                      {'fields': ['question_text']}),

    ('Date information',        {'fields': ['pub_date'], 'classes': ['collapse']}),

  ]


admin.site.register(Question, QuestionAdmin)


이렇게 collapse class도 제공하여 HTML arbitrary HTML classes를 각각의 fieldset에 적용시킬 수 있다.

*Adding related objects
- Question은 다수의 Choices를 가지는데 관리자 페이지는 아직까지 그것을 보여주지 못하고 있다.
 그러나 이 문제를 해결하는 두가지 방법이 있다.

1.우리가 Question을 했던 것처럼 admin과 함께 Choice를 등록하는 것이다.

from django.contrib import admin


from .models import Question,Choice


# Register your models here.

class QuestionAdmin(admin.ModelAdmin):

  fieldsets = [

    (None,                      {'fields': ['question_text']}),

    ('Date information',        {'fields': ['pub_date'], 'classes': ['collapse']}),

  ]


admin.site.register(Question, QuestionAdmin)

admin.site.register(Choice)


Choices 옵션이 활성화되었고, "Add Choice" 폼을 누르면 다음과 같이 화면이 뜬다.


여기서 Question 필드가 DB의 모든 question을 선택할 수 있게 되어있고, Django는 외래키가 select box로서 표현된다는 것을 알아야만 한다.


그러나 이것은 비효율적이다. Question 객체를 생성할 때 복수의 Choices를 바로 추가할 수 있다면 그게 더 좋을 것 같다.


register()를 지우고, Choice 모델을 불러와라.  그리고 Question 등록 코드를 수정하라.


-polls/admin.py


from django.contrib import admin


from .models import Question,Choice


# Register your models here.

class ChoiceInline(admin.StackedInline):

  model = Choice

  extra = 3


class QuestionAdmin(admin.ModelAdmin):

  fieldsets = [

    (None,                      {'fields': ['question_text']}),

    ('Date information',        {'fields': ['pub_date'], 'classes': ['collapse']}),

  ]

  inlines = [ChoiceInline]


admin.site.register(Question, QuestionAdmin)


이것은 Django에게 말해준다. "Choice 객체들이 Question admin page위에서 수정될 것이다. 디폴트로, 3 choices를 위한 충분한 필드들을 제공하라."



extra 속성에 의해 3개의 Choice 필드가 생성되었다.


추가도 가능하다.

Additional slot added dynamically


그러나 한가지 문제가 또 있다. 이것은 어마어마한 화면 공간을 차지한다. 이러한 이유에서 Django는 a tabular way of displaying inline related objects를 제공한다. 다음코드를 수정하라.


-polls/admin.py

# Register your models here.

class ChoiceInline(admin.TabularInline):

  model = Choice

  extra = 3


StackedInline대신에 TabularInline과 함께 관계된 객체들은 더 압축적이고 table-based 형식을 가지게 된다.

Add question page now has more compact choices


*Customize the admin change list
자, 이제 "change list" page를 보자. 

디폴트로, Django는 각 객체의 str()를 보여준다. 그러나 때로는 개개인의 필드를 보여준다면 도 유용할 수 있다. 이것을 하기 위해서, list_display 관리자 속성을 사용해야 한다. 이 속성은 객체에 대한 change list위의 컬럼들으로서 보여주기 위한 필드네임들의 튜플이다. 


-polls/admin.py

class QuestionAdmin(admin.ModelAdmin):

  fieldsets = [

    (None,                      {'fields': ['question_text']}),

    ('Date information',        {'fields': ['pub_date'], 'classes': ['collapse']}),

  ]

  inlines = [ChoiceInline]

  list_display = ('question_text', 'pub_date')


단순히 보기 좋게 하기 위해 was_published_recently 도 포함시키자.


class QuestionAdmin(admin.ModelAdmin):

  fieldsets = [

    (None,                      {'fields': ['question_text']}),

    ('Date information',        {'fields': ['pub_date'], 'classes': ['collapse']}),

  ]

  inlines = [ChoiceInline]

  list_display = ('question_text', 'pub_date', 'was_published_recently')



다음과 같이 변화하였다.

헤더를 클릭하면 정렬을 할 수 있다.(was_published_recently를 제외하고; 이유는 arbitrary method의 결과 정렬은 지원되지 않기 때문이다. 또한 이 메서드 컴럼의 헤더는 메서드의 이름이다.)


우리는 이 메서드에 대해서 몇가지 속성을 줌으로써 표현방식을 향상시킬 수 있다.


class Question(models.Model):# Inherited 'django.db.models.Model'

  question_text = models.CharField(max_length=200)

  pub_date = models.DateTimeField('date published')

  def __str__(self): # __unicode__ on Python 2

    return self.question_text

  def was_published_recently(self):

    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

  was_published_recently.admin_order_field = 'pub_date'

  was_published_recently.boolean = True

  was_published_recently.short_description = 'Published recently?'


For more information on these method properties, see list_display.


그리고 polls/admin.py 파일을 다시 수정하고, 향상된 것을 Question change list page에 추가하라.(filter using the list_filter)


QuestionAdmin에 다음 라인을 추가하라.


list_filter = ['pub_date']


그럼 "Filter" 라는 사이드바가 생성된다.



이 형태의 필터는 우리가 필터링 하는 필드의 타입에 의존한다. pub_date가 DateTimeField이기 때문에, Django는 적절한 필드 옵션을 부여할 수 있다.

다음으로 search capability를 추가해보자.

search_fields = ['question_text']


이것은 a search box를 change list 최상위에 추가해준다. 


Now’s also a good time to note that change lists give you free pagination. The default is to display 100 items per page. Change list paginationsearch boxesfiltersdate-hierarchies, and column-header-ordering all work together like you think they should.




*Customizing the admin look and feel
-템플릿은 바꾸기 쉽다. 그러나 Django's template system을 써야 한다.

1.Customizing your project's templates
-templates directory를 우리 프로젝트 디렉토리 안에 생성하자.(manage.py만을 포함하고있는) 템플릿은 Django가 접속가능한 우리의 파일시스템 위에 어디에서나 살 수 있다. 그러나, 프로젝트내에서 템플릿을 유지하고 있는 것이 좋은 convention 이다.

settings file(mysite/settings.py)을 열고 DIRS 옵션을 TEMPLATES 세팅 안에 추가하자.

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, 'templates')],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',

                'django.contrib.auth.context_processors.auth',

                'django.contrib.messages.context_processors.messages',

            ],

        },

    },

]


DIRS는 a list of filesystem directories to check when loading Django templates; it's a search path.
이제 templates내부에 admin이라는 디렉토리를 생성하고 admin/base_site.html템플릿(within the default Django admin template directory in the source code of Djangoitself(django/contrib/admin/templates))을 복사해오자.

code of Django itself (django/contrib/admin/templates) into that directory.

Where are the Django source files?

If you have difficulty finding where the Django source files are located on your system, run the following command:

$ python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"

EminentStarui-MacBook-Pro:mysite eminentstar$ python -c "

> import sys

> sys.path = sys.path[1:]

> import django

> print(django.__path__)"

['/Library/Python/2.7/site-packages/django']


위치

/Library/Python/2.7/site-packages/django/contrib/admin/templates/admin


옮기자.

cp base_site.html ~/Documents/Programming/PythonProgramming/mysite/templates/admin/


base_site.html

{% extends "admin/base.html" %}


{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}


{% block branding %}

<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>

{% endblock %}


{% block nav-global %}{% endblock %}

~                                        


우리는 이 접근을 너가 어떻게 템플릿들을 오버라이드 하는지 가르치기 위해 사용한다.

실제 프로젝트에에서는 너는 아마 "django.contrib.admin.AdminSite.site_header" attribute를 특정한 커스터마이징을 더 쉽게 하기위해 사용할 것이다.


이 템플릿 파일은 다량의 텍스트 ({% block title %} 나 {{ title }} 와 같은)를 포함하고 있다.

여기서 "{%" 와 "{{" 태그는 Django's template language의 일부이다. Django renders가 admin/base_site.html을 읽을때, 이 템플릿 랭귀지가 최후의 HTML 페이지를 생산하기 위해 평가되어질 것이다.

Part 3에서 자세히 다룰 것이다.


어떤 Django's default admin templates는 오버라이드가 가능하다는 것에 주목하라. 템플릿을 수정하기 위해 base_site.html에서 햇던것과 같은 것을 하면 된다. 복사해서 넣고 수정하면 된다.



*Customizing your application's templates

DIRS 옵션이 비어있다면 어떻게 Django는 디폴트 admin templates를 찾을까? 정답은 APP_DIRS가 True로 설정돼있는 이래로, Django는 자동적으로 애플리케이션 패키지내의 templates/ 서브 디렉토리를 찾을 것인데 fallback으로써..


*Customize the admin index page


django.contrib.admin의 index.html을 나의 랩의 templates/admin/로 옮기자.









댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함