티스토리 뷰

WEB/Django

Customizing the Django Admin

취뽀가자!! 2018. 12. 23. 15:24

Customizing the Django Admin

String Representation

위의 그림과 같이 화면에 출력이 되면 이미지가 누가 올리고 어떤 내용의 이미지인지 알 수 없다. 그래서 String representation을 사용해 간략하게 내용을 표시할려 한다.


class Image(TimeStampedModel):

""" Image Model """
file = models.ImageField()
location = models.CharField(max_length=140)
caption = models.TextField()
creator = models.ForeignKey(user_models.User, on_delete=models.PROTECT, null=True,)

def __str__(self):
return '{} - {}'.format(self.location, self.caption)


__str__(self)함수를 보면 자기 자신의 location과 caption을 리턴해 준다. 어드민 페이지를 새로고침해서 봐 보자



Admin Panel

어드민 패널에는 정말 많은 옵션들이 있지만 그 중에서 list_display, list_display_links, list_filter, search_fields를 소개해 보겠다.

List_display

list_display를 사용하면 어드민 페이지에서 각 필드에 저장된 내용을 볼 수 있다. 코드는 아래와 같다.

@admin.register(models.Image)
class ImageAdmin(admin.ModelAdmin):

list_display = (
'file',
'location',
'caption',
'creator',
'created_at',
'updated_at',
)


Image App에 있는 admin.py에 models안에 Image클래스를 데코레이터를 하고 ImageAdmin클래스에 list_display를 위와 같이 작성을 하면 어드민 페이지에서 각 필드의 내용을 확인할 수 있다.


List_display_links

예를 들어 location에 링크를 걸고 싶으면 다음과 같이 코딩해 주면 된다.
@admin.register(models.Image)
class ImageAdmin(admin.ModelAdmin):

list_display_links = (
'location',
)
list_display = (
'file',
'location',
'caption',
'creator',
'created_at',
'updated_at',
)


어드민 페이지를 새로고침해 보자



Location에 링크가 생긴 것을 확인할 수 있다. 링크를 눌러보면 수정을 할 수 있게 된다.



Search_fields와 List_filter

검색기능과 필터 기능을 추가하고 싶으면 다음과 같이 코딩하면 된다.

@admin.register(models.Image)
class ImageAdmin(admin.ModelAdmin):

list_display_links = (
'location',
)
search_fields = (
'location',
'caption',
)

list_filter = (
'location',
'creator'
)

list_display = (
'file',
'location',
'caption',
'creator',
'created_at',
'updated_at',
)


어드민 페이지를 새로고침 해 보면


이렇게 검색바와 필터창이 생긴 것을 확인할 수 있다.










'WEB > Django' 카테고리의 다른 글

로그인/로그아웃/회원가입 기능 구현  (0) 2019.01.07
JWT(Json Web Token)  (0) 2019.01.07
The Request Object in Django  (0) 2018.12.25
Hidden Model Fields in Django  (0) 2018.12.24
Creating the URLS and Testing the images serializers  (0) 2018.12.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함