Django

Django 기초 5주차 2_taggit_Sparta Coding Club

끈끈 2023. 4. 6. 00:25

 

django taggit 설치하기

 

장고 태그모듈 다운:

pip install django-taggit
pip install django-taggit-templatetags2

 

혹은, Python Interpreter에서 django-taggit을 Install Package 해줘도 된다

 

settings에 추가

 

mySpartaSns/settings.py:

INSTALLED_APPS = [
    'taggit.apps.TaggitAppConfig',
    'taggit_templatetags2',
]

# 태그 모듈에 필요한 정보 추가
TAGGIT_CASE_INSENSITIVE = True
TAGGIT_LIMIT = 50

 

tweet/models.py:

from django.db import models
from user.models import UserModel
from taggit.managers import TaggableManager # 우리 글에 태그를 넣게 해주는 매니저

class TweetModel(models.Model):
    class Meta:
        db_table = "tweet"

    author = models.ForeignKey(UserModel, on_delete=models.CASCADE)
    content = models.CharField(max_length=256)
    tags = TaggableManager(blank=True) # 비어있어도 작동되게
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

 

데이터베이스에 알려주기

python manage.py makemigrations
python manage.py migrate

 


 

django taggit 사용하기

 

tweet/views.py:

@login_required
def tweet(request):
    if request.method == 'GET':
        user = request.user.is_authenticated
        if user:
            all_tweet = TweetModel.objects.all().order_by('-created_at')
            return render(request, 'tweet/home.html', {'tweet': all_tweet})
        else:
            return redirect('/sign-in')
    elif request.method == 'POST':
        user = request.user
        content = request.POST.get('my-content', '')
        tags = request.POST.get('tag', '').split(',') # 태그를 웹 화면에서 장고 서버로 받아옴
        if content == '':
            all_tweet = TweetModel.objects.all().order_by('-created_at')
            return render(request, 'tweet/home.html', {'error': '글은 공백일 수 없습니다.', 'tweet': all_tweet})
        else:
            my_tweet = TweetModel.objects.create(author=user, content=content)
            for tag in tags: # 태그 목록 분류
                tag = tag.strip() # 공백 제거
                if tag != '': # 태그에 내용이 있다면
                    my_tweet.tags.add(tag)
            my_tweet.save()
            return redirect('/tweet')

+

# django-taggit 모듈에서 정해놓은 것
from django.views.generic import ListView, TemplateView

class TagCloudTV(TemplateView): # 태그들을 모아놓는 태그클라우드
    template_name = 'taggit/tag_cloud_view.html'

class TaggedObjectLV(ListView): # 태그들을 모아서 화면에 전달
    template_name = 'taggit/tag_with_post.html'
    model = TweetModel

    def get_queryset(self):
        return TweetModel.objects.filter(tags__name=self.kwargs.get('tag'))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tagname'] = self.kwargs['tag']
        return context

 

tweet/urls.py:

path('tag/', views.TagCloudTV.as_view(), name='tag_cloud'), # 추가
path('tag/<str:tag>/', views.TaggedObjectLV.as_view(), name='tagged_object_list'), # 추가

 

templates/tweet/home.html:

</textarea>
<div class="mt-3 row"> # 추가
    <label for="tag"
           class="col-sm-2 col-form-label">이 글의 태그</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" name="tag" id="tag"
               placeholder="콤마(,)로 구분 해 주세요">
    </div>
</div> #####

 

templates/tweet/home.html:

templates/tweet/tweet_detail.html:

<div class="media-body">
    <h5 class="mt-0">{{ tw.content }}</h5>
    {% if tweet.tags.all %} # 추가
        {% for tag in tweet.tags.all %}
            <a style="text-decoration: none"
               href="{% url 'tagged_object_list' tag.name %}">
            <span class=" badge rounded-pill bg-success">
                {{ tag.name }}
            </span>
            </a>
        {% endfor %}
        -<a style="text-decoration: none"
            href="{% url 'tag_cloud' %}">TagCloud</a>
    {% endif %} #####
</div>

 

django-taggit

 

templates/taggit/tag_with_post.html:

더보기

{% extends "base.html" %}

{% block title %}태그 글 리스트{% endblock %}

{% block content %}

    <div class="container">
        <h3 class="mt-2">Posts for tag - {{ tagname }}</h3>
        <hr>
        <div class="card">
            <div class="card-body">
                {% for tweet in object_list %}
                    <h4>
                        <a href="/tweet/{{ tweet.id }}">{{ tweet.content }}</a>
                    </h4>
                    {{ tweet.updated_at|timesince}}
                    <p> {{ tweet.author }}</p>
                {% endfor %}
            </div>
        </div>
    </div>
{% endblock %}

 

templates/taggit/tag_cloud_post.html:

더보기

{% extends "base.html" %}

{% block title %}태그 클라우드{% endblock %}


{% block content %}

    <div class="container timeline-container">
        <div class="tag-cloud">
            {% load taggit_templatetags2_tags %}
            {% get_tagcloud as tags %} <!--모든 태그 추출해서 tags변수에 할당-->
            {% for tag in tags %}
                    <a style="text-decoration: none" href="{% url 'tagged_object_list' tag.name %}">
                        <span class="badge rounded-pill bg-primary">
                            {{ tag.name }}({{ tag.num_times }})
                        </span>
                    </a>
            {% endfor %}
        </div>
    </div>

{% endblock %}

 

tweet 페이지