πŸ‘¦ 내일배움캠프/TIL(Today I Learned)

TIL_220620_DRF κ°•μ˜

  • -

μ΄λ²ˆμ—λŠ” serializer λ₯Ό μ‘μš©ν•˜λŠ” 심화 과정을 λ°Ÿμ•˜λ‹€.

 

- permissions.py 둜 κ΄€λ¦¬μž 및 μ‚¬μš©μžμ˜ κΆŒν•œμ„ λΆ€μ—¬ν•˜κ³ 

- 상황에 λ”°λ₯Έ 쑰건을 μ •μ˜ν•΄μ„œ 쑰회 및 μˆ˜μ • κΆŒν•œμ„ 뢄리할 수 있음.

- ex) 7일이 μ§€λ‚˜μ§€ μ•Šμ€ μ‚¬μš©μžλŠ” κ²Œμ‹œκΈ€ μž‘μ„± λΆˆκ°€ λ“±

 

단 μ‹œκ°„μ— λ„ˆλ¬΄λ‚˜ λ§Žμ€ μ •λ³΄λŸ‰μ„ μŠ΅λ“ν•˜λ €λ‹ˆ

 

λ‡Œκ°€ μ₯κ°€ λ‚˜κΈ° μ‹œμž‘ν–ˆλ‹€..

 

계속 μ£Όμž…ν•˜λ €λŠ” 데이터λ₯Ό λ‚˜λ§Œμ˜ λ°©λ²•μœΌλ‘œ μ‘°κΈˆμ”©..

 

μ‘°κΈˆμ”© μ†Œν™”ν•˜κ³ μž ν•œλ‹€..

 

λΆ€λ”” μ²΄ν•˜μ§€ 말고, 잘 ν‘μˆ˜ν•  수 있기λ₯Ό...

 


μ—λŸ¬ λ…ΈνŠΈ

λŒ€λΆ€λΆ„ μ˜€νƒ€λ‘œ μΈν•œ μ—λŸ¬..

 

λ―ΈμΉ˜κ²ƒλ‹€..


4일차 과제 심화


1. admin νŽ˜μ΄μ§€μ— user admin을 λ“±λ‘ν•˜κ³ , userprofile ν…Œμ΄λΈ”μ„ user admin νŽ˜μ΄μ§€μ—μ„œ 같이 보고 μ„€μ • ν•  수 μžˆλ„λ‘ ν•΄μ£Όμ„Έμš”

class UserAdmin(BaseUserAdmin):
    list_display = ('id', 'username', 'fullname', 'email')
    list_display_links = ('username', )
    list_filter = ('username', )
    search_fields = ('username', 'email', )

    fieldsets = (
        ("info", {'fields': ('username', 'password', 'email', 'fullname', 'join_date',)}),
        ('permissions', {'fields':('is_admin', 'is_active', )}),)

    filter_horizontal = []

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('username', 'join_date', )
        else:
            return ('join_date', )


2. article ν…Œμ΄λΈ”에 <λ…ΈμΆœ μ‹œμž‘ μΌμž, λ…ΈμΆœ μ’…λ£Œ μΌμž>을 μΆ”κ°€ν•΄μ£Όμ„Έμš”

class Article(models.Model):
    user = models.ForeignKey('user.User', verbose_name="κΈ€ μž‘μ„±μž", on_delete=models.CASCADE)
    title = models.CharField("κΈ€ 제λͺ©", max_length=50)
    content = models.TextField("κΈ€ λ³Έλ¬Έ")
    category = models.ManyToManyField(Category, verbose_name="μΉ΄ν…Œκ³ λ¦¬")
    exposure_start = models.DateField('λ…ΈμΆœ μ‹œμž‘ 일자', auto_now_add=True)
    exposure_end = models.DateField('λ…ΈμΆœ μ’…λ£Œ 일자', auto_now=True)

3. article view에 κ²Œμ‹œκΈ€ 쑰회 κΈ°λŠ₯을 λ§Œλ“€λ˜, ν˜„μž¬ 일자λ₯Ό κΈ°μ€€μœΌλ‘œ λ…ΈμΆœ μ‹œμž‘ μΌμžμ™€ λ…ΈμΆœ μ’…λ£Œ 일자 사이에 μžˆλŠ” ν•­λͺ©λ“€λ§Œ 리턴해주도둝 ν•„ν„°λ₯Ό μ„€μ •ν•΄μ£Όμ„Έμš”
 - 리턴 λ°μ΄ν„°λŠ” κ²Œμ‹œκΈ€ μž‘μ„±μΌ κΈ°μ€€μœΌλ‘œ μ •λ ¬ν•˜μ—¬ 졜근 μ“΄ 글이 κ°€μž₯ λ¨Όμ € μ˜¬λΌμ˜€λ„λ‘ ν•΄μ£Όμ„Έμš”

class ArticleView(APIView):
    # permission_classes = [permissions.IsAuthenticated]
    # permission_classes = [permissions.AllowAny]

    permission_classes = [RegisterdMoreThanThreeDaysUser]   # μ»€μŠ€ν…€ permissions

    def get(self, request):
        user = request.user
        today = timezone.now()
        articles = ArticleModel.objects.filter(
            exposure_start__lte = today,
            exposure_end__gte = today,
        ).order_by("-id")

        serializer = ArticleSerializer(articles, many=True).data

        # titles = [article.title for article in articles] # list μΆ•μ•½ 문법

        # titles = []

        # for article in articles:
        #     titles.append(article.title)

        return Response(serializer, status=status.HTTP_200_OK)


4. κΈ°μ‘΄ article μƒμ„± κΈ°λŠ₯을 μœ μ§€ν•˜λ˜, article은 admin user ν˜Ήμ€ κ°€μž… ν›„ 7일이 μ§€λ‚œ μ‚¬μš©μžλ§Œ μƒμ„± κ°€λŠ₯ν•˜λ„λ‘ ν•΄μ£Όμ„Έμš”

 - μ‘°νšŒλŠ” 둜그인 ν•œ μ‚¬μš©μžμ— λŒ€ν•΄μ„œλ§Œ κ°€λŠ₯ν•˜λ„λ‘ μ„€μ •ν•΄μ£Όμ„Έμš”

class GenericAPIException(APIException):
    def __init__(self, status_code, detail=None, code=None):
        self.status_code = status_code
        super().__init__(detail=detail, code=code)


class IsAdminOrAuthenticatedReadOnly(BasePermission):
    '''
    admin μ‚¬μš©μžλŠ” λͺ¨λ‘ κ°€λŠ₯, 둜그인 μ‚¬μš©μžλŠ” 쑰회만 κ°€λŠ₯
    '''
    SAFE_METHODS = ('GET', )
    message = 'μ ‘κ·Ό κΆŒν•œμ΄ μ•„λ‹™λ‹ˆλ‹€.'

    def has_permission(self, request, view):
        user = request.user

        if not user.is_authenticated:
            response ={
                "detail" : "μ„œλΉ„μŠ€λ₯Ό μ΄μš©ν•˜κΈ° μœ„ν•΄ 둜그인 ν•΄μ£Όμ„Έμš”."
            }
            raise GenericAPIException(status_code=status.HTTP_401_UNAUTHORIZED, detail=response)

        if user.is_authenticated and request.method in self.SAFE_METHODS:
            return True

        if user.is_authenticated and user.is_admin or \
            user.join_date < (datetime.now().date() - timedelta(days=7)):
            return True

        return False
 

'πŸ‘¦ 내일배움캠프 > TIL(Today I Learned)' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

TIL_220623_λ”₯λŸ¬λ‹  (0) 2023.01.01
TIL_220621_DRF κ°•μ˜  (0) 2023.01.01
TIL_220617_DRF κ°•μ˜  (0) 2023.01.01
TIL_220616_DRF κ°•μ˜  (0) 2023.01.01
TIL_220615_DRF κ°•μ˜  (0) 2023.01.01
Contents

ν¬μŠ€νŒ… μ£Όμ†Œλ₯Ό λ³΅μ‚¬ν–ˆμŠ΅λ‹ˆλ‹€

이 글이 도움이 λ˜μ—ˆλ‹€λ©΄ 곡감 λΆ€νƒλ“œλ¦½λ‹ˆλ‹€.