티스토리 뷰

● 태그 달기

 

 

- Post 객체에서 태그 필드는 TaggableManager() 모듈을 사용했다. 아래의 공식문서에서 모듈 사용법을 보고 따라했다.

https://django-taggit.readthedocs.io/en/latest/api.html

 

The API — django-taggit 1.2.0 documentation

After you’ve got your TaggableManager added to your model you can start playing around with the API. Filtering To find all of a model with a specific tags you can filter, using the normal Django ORM API. For example if you had a Food model, whose TaggableM

django-taggit.readthedocs.io

- 태그 기능을 사용하기 위해서는 게시물을 작성하는 폼에 태그필드를 추가하는 것, 입력한 태그를 객체에 저장하는 것 그리고 게시물 상세보기에서 태그를 나타내는 것 총 세 가지 작업을 추가해야한다. 

 

 

 

templates/post_write.html 

- 게시글을 작성하는 폼에 태그 필드를 추가한다.

- models.py 에서 태그 필드 이름을 tags 라고 설정하였으니 그에 맞춰서 폼 필드를 추가한다. 

<form method = "post" action = "{% url 'post_write' %}" enctype = "multipart/form-data" class = "col-lg-8 col-md-10 mx-auto">
  {% csrf_token %}
  <div class = "form-group row">
  	<label for = "title">제목</label>
  	<input type = "text" class = "form-control" name = "title" placeholder="제목을 입력해주세요.">
  </div>
  <div class = "form-group row">
  	<label for = "content">내용</label>
  	<textarea class = "form-control" name = "content" rows = "7"></textarea>
  </div>
  <div class = "form-group row">
  	<label for = "content">사진 첨부</label>
  	<input type = "file" class = "form-control" name = "image">
  </div>
  <div class = "form-group row">
  	<label for = "tags">태그 달기</label>
  	<input type = "text" class = "form-control" name = "tags">
  </div>
  <div class = "form-group row float-right">
  	<button type = "submit" class = "btn btn-primary">저장하기</button>
  </div>
</form>

 

 

 

 

post/views.py/post_write

- 전달받은 게시물 작성 폼에서 태그 값은 콤마와 공백이 포함되어있다. 따라서, 일단 콤마를 기준으로 태그를 분리하고 양 끝 공백을 제거해야한다. 

- split(',') 을 이용해서 태그를 콤마로 분리해서 리스트 tags에 저장한다. 

- 태그값은 post 객체가 모두 생성되고 난 이후에 post.tags.add 를 사용하여 태그값을 추가한다. Post.objects.create 의 파라미터에 바로 넣지 않는 이유는 add 함수를 사용하기 위해서는 post.tags에 대한 정보(객체)가 미리 정의되어 있어야 하기 때문이다. 

- for 문을 이용하여 tags 리스트에서 태그를 하나씩 꺼내고 strip() 으로 양 끝 공백을 없애준 다음, add 함수를 이용하여 태그를 저장한다.

@login_required
def post_write(request):
    errors = []
    if request.method == 'POST':
        title = request.POST.get('title', '').strip()
        content = request.POST.get('content', '').strip()
        image = request.FILES.get('image')
        tags = request.POST.get('tags', '').split(',')
        if not title:
            errors.append('제목을 입력하세요.')
        if not content:
            errors.append('내용을 입력하세요.')
        if not errors:
            post = Post.objects.create(user=request.user, title = title, content = content, image = image)
            for tag in tags:
                tag = tag.strip()
                post.tags.add(tag)
            return redirect(reverse('post_detail', kwargs={'post_id': post.id}))
    return render(request, 'post_write.html', {'user':request.user, 'errors':errors})

 

 

 

templates/post_detail.html

- 게시물 상세보기 페이지에서 태그 값을 표시하는 것은 간단하다. views.py/post_detail 로직에서 전달받은 post 객체 정보에서 tags 값을 꺼내고 출력한다.

<div class = "row">
    <!-- 태그 달기 -->
    <div class="col-lg-8 col-md-10 mx-auto">
        {% for tag in post.tags.all %}
            <span class="badge badge-dark">
            #{{ tag.name }}
            </span>
        {% endfor %}
    </div>

    <!-- 소셜 공유 -->
    <div class="col-lg-8 col-md-10 mx-auto">
    </div>
</div>

 

 

 

 

 

실행 결과

 

- 아래와 같이 입력한다. 태그 값은 콤마를 이용하여 작성한다. 공백을 앞에 붙이건, 뒤에 붙이건 어차피 공백은 제거되므로 상관 없다. 

- 만약에 "뉴발란스", " 뉴발란스", "뉴발란스 " 세 개의 태그를  입력한다면 공백이 제거되어 동일한 문자열로 인식하므로 하나의 값만 저장된다.

 

 

- 게시물 상세보기 페이지에서 태그 값이 제대로 저장되어 출력되는 것을 확인할 수 있다.

 

댓글