Heesung Yang

[Django] Admin Customization

JSON Field 이쁘게 출력하기

  • Pygments 패키지 설치

    ~$ pip install Pygments
    
  • models.py

    from django.db import models
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        data = models.JSONField()
        pub_date = models.DateTimeField('date published')
    
  • admin.py

    import json
    
    from django.contrib import admin
    from django.utils.safestring import mark_safe
    
    from pygments import highlight
    from pygments.lexers.data import JsonLexer
    from pygments.formatters.html import HtmlFormatter
    
    
    from .models import Question
    
    @admin.register(Question)
    class QuestionAdmin(admin.ModelAdmin):
        list_display = ('id', 'question_text')
        readonly_fields = ('formatted_json_data',)
    
        def formatted_json_data(self, obj):
            data = json.dumps(obj.data, sort_keys=True, indent=2)
            formatter = HtmlFormatter(style='dracula')
            pretty_data = highlight(data, JsonLexer(), formatter)
            style = "<style>" + formatter.get_style_defs() + "</style><br>"
            return mark_safe(style + pretty_data)
    
    
    

django-admin-json-field-formatted

시간 포맷 변경

모든 필드를 list_display에 설정하기

  • models.py

    from django.db import models
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        is_answered = models.BooleanField(default=False)
    
  • admin.py

    from django.contrib import admin
    
    from .models import Question
    
    @admin.register(Question)
    class QuestionAdmin(admin.ModelAdmin):
        # 이렇게 필드명을 직접 하나하나 나열하는 대신
        # list_display = ('id', 'question_text', 'pub_date', 'is_answered')
    
        # 아래와 같이 모든 필드 가져올 수 있음
        list_display = [field.name for field in Question._meta.get_fields()]
    
    
  • 적용 화면 list display

  • 그러나 아래와 같이 다른 모델과 ForeignKey, ManyToMany 관계에 있다면 에러 발생!

    • models.py

      from django.db import models
      
      class Question(models.Model):
          question_text = models.CharField(max_length=200)
          pub_date = models.DateTimeField('date published')
          is_answered = models.BooleanField(default=False)
      
      
      class Choice(models.Model):
      
          # Question 모델과 ForeignKey 관계를 갖음
          question = models.ForeignKey(Question, on_delete=models.CASCADE)
      
          choice_text = models.CharField(max_length=200)
          votes = models.IntegerField(default=0)
      
    • 에러

      AttributeError: Unable to lookup 'choice' on Question or QuestionAdmin