'WSGIRequest' object has no attribute 'author'

Joohyung Park·2024년 3월 10일

버그

목록 보기
9/12

문제

포스트 상세 페이지에 댓글 기능을 추가하던 중, 위와 같은 오류가 발생했다. 기본적으로 WSGIRequest 객체에는 author 속성이 없어서 발생한다고 한다. 따라서 author 대신 user 를 사용하여 현재 유저 정보를 접근하면 된다.

추가적으로, WSGIRequest가 궁금하여 찾아보았다.

WSGI

웹서버와 프레임워크(Django), 앱을 연결해주는 Python의 표준 API라고 한다. 웹서버와 웹앱의 소통을 도와주는 번역기 같은 역할을 한다고 보면 된다.

Django의 내장 서버는 WSGI 기능을 자체적으로 포함하고 있다. 나중에 다시 배울 내용이기에 이정도만 보도록 하자.

해결

# views.py
def new_comment(request, pk):
    if request.user.is_authenticated:
        post = get_object_or_404(Post, pk=pk)

        if request.method == "POST":
            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():
                comment = comment_form.save(commit=False)
                comment.post = post
                # comment.author = request.author
                comment.author = request.user
                comment.save()
                return redirect(comment.get_absolute_url())
        else:
            return redirect(post.get_absolute_url())
    else:
        raise PermissionDenied

comment.author = request.author로 되있던 부분을 request.user로 수정하였다.

참고

관련 블로그

profile
익숙해지기 위해 기록합니다

0개의 댓글