본문 바로가기
App Programming/Django

[Django] Search (검색 기능)

by goatlab 2023. 2. 17.
728x90
반응형
SMALL

Search (검색 기능)

 

웹 애플리케이션의 일반적인 작업은 사용자 입력으로 데이터베이스의 일부 데이터를 검색하는 것이다. 간단한 경우 범주별로 개체 목록을 필터링할 수 있다. 보다 복잡한 사용 사례에서는 가중치, 범주화, 강조 표시, 여러 언어 등을 사용한 검색이 필요할 수 있다.

 

home.html

 

topics별로 browse 가능한 home.html을 구현한다.

 

{% extends 'main.html' %}

{% block content %}

<style>
    .home-container{
        display: grid;
        grid-template-columns: 1fr 3fr;
    }
</style>

<div class="home-container">
    <div>
        <h3>Browse Topics</h3>
        <hr>

        <div>
            <a href="{% url 'home' %}">All</a>
        </div>

        {% for topic in topics %}
            <div>
                <a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a>
            </div>
        {% endfor %}
    </div>

    <div>
        <h5>{{room_count}} rooms available</h5>
        <a href="{% url 'create-room' %}">Create Room</a>

    <div>
        {% for room in rooms %}
            <div>
                <a href="{% url 'update-room' room.id %}">Edit</a>
                <a href="{% url 'delete-room' room.id %}">Delete</a>
                <span>@{{room.host.username}}</span>
                <h5>{{room.id}} -- <a href  = "{% url 'room' room.id %}">{{room.name}}</a></h5>
                <small>{{room.topic.name}}</small>
                <hr>
            </div>

        {% endfor %}
    </div>

    </div>
    
</div>

{% endblock content %}

 

navbar.html

 

필터링 검색이 가능한 navbar.html을 다음과 같이 작성한다.

 

<a href = "/">
    <h1>LOGO</h1>
</a>

<form method="GET" action="{% url 'home' %}">
    <input type="text" name="q" placeholder="Search Rooms..." />
</form>

<hr>

 

home.html

 

from django.shortcuts import render, redirect
from django.db.models import Q
from .models import Room, Topic
from .forms import RoomForm

def home(request):
    q = request.GET.get('q') if request.GET.get('q') != None else ''
    rooms = Room.objects.filter(
        Q(topic__name__icontains = q) |
        Q(name__icontains=q) |
        Q(description__icontains=q)
        )
    topics = Topic.objects.all()
    room_count = rooms.count()
    
    context = {'rooms': rooms, 'topics': topics, 'room_count': room_count}
    
    return render(request, 'base/home.html', context)

def room(request, pk):
    room = Room.objects.get(id = pk)

    context = {'room': room}
    
    return render(request, 'base/room.html', context)

def createRoom(request):
    form = RoomForm()
    if request.method == 'POST':
        form = RoomForm(request.POST)
        if form.is_valid():
            form.save()
            
            return redirect('home')
    
    context = {'form': form}
    
    return render(request, 'base/room_form.html', context)

def updateRoom(request, pk):
    room = Room.objects.get(id = pk)
    form = RoomForm(instance = room)
    
    if request.method == 'POST':
        form = RoomForm(request.POST, instance = room)
        if form.is_valid():
            form.save()
            
            return redirect('home')
    
    context = {'form': form}
    return render(request, 'base/room_form.html', context)

def deleteRoom(request, pk):
    room = Room.objects.get(id = pk)
    if request.method == 'POST':
        room.delete()
        return redirect('home')
    
    return render(request, 'base/delete.html', {'obj':room})

 

https://docs.djangoproject.com/en/4.1/topics/db/search/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 

728x90
반응형
LIST

'App Programming > Django' 카테고리의 다른 글

[Django] 기본 요소 (2)  (0) 2023.02.20
[Django] 기본 요소 (1)  (0) 2023.02.20
[Django] CRUD  (0) 2023.02.17
[Django] Admin (Room)  (0) 2023.02.17
[Django] 템플릿 (Templates) (2)  (0) 2023.02.02