hotamul의 개발 이야기

[hotamul] Django Admin Action without selecting objects 본문

project/share-blog

[hotamul] Django Admin Action without selecting objects

hotamul 2022. 10. 10. 23:35

Django Admin에서 Item을 선택하지 않고 Go(Aciton) 버튼을 클릭하면 위와 같이 Item이 선택되어야 한다는 경고 메시지를 볼 수 있다.

share-blog에 블로그들의 (velog - giruboy, tistory - hotamul) 최근 게시물을 가져오는 기능을 Django Admin Action을 이용해 구현하려고 하기 때문에 해당 Error가 발생하지 않도록 해야한다.


해결 방법

  1. action method 추가
    # blog/admin.py
    ...
    @admin.register(Post)
    class PostAdmin(admin.ModelAdmin):
     list_display = (
         'id',
         'category',
    ...
     actions = ['get_the_latest_blog_posts', ]
     def get_the_latest_blog_posts(self, request, queryset):
         cnt = len(queryset)
         crawlers = create_crawlers()
         for c in crawlers:
             c.crawl()
         cnt = Post.objects.all().count() - cnt
         if cnt:
             msg = '{} posts were created successfully.'.format(cnt)
         else:
             msg = 'It is already up to date.'
         self.message_user(request, msg, messages.SUCCESS)
    ...
  2. changelist_view overriding
# blog/admin.py
...
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'category',
...
    def changelist_view(self, request, extra_context=None):
        if 'action' in request.POST \
                and request.POST['action'] == 'get_the_latest_blog_posts':
            if not request.POST.getlist(ACTION_CHECKBOX_NAME):
                post = request.POST.copy()
                for u in Post.objects.all():
                    post.update({ACTION_CHECKBOX_NAME: str(u.id)})
                request._set_post(post)
        return super(PostAdmin, self).changelist_view(request, extra_context)
...

만약 request.POST 'action'이름이 'get_the_latest_blog_posts'이고 request에 item list가 한 개도 없다면 (selected된 아이템이 없다면) 현재 모든 Postrequest에 추가한다.


Post.objects.all()로 처리한 이유는 나중에 저장되어 있는 게시물들의 url과 크롤링을 통해 가져온 url과 비교해서 저장되어 있지 않은 url만 크롤링 하기 위해서 이다.


참고: django admin action without selecting objects - Stack Overflow

Comments