Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. Search
  5. Single Search Result

Single Search Result

# mysearchapp/models.py
from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Run Migrations:

python manage.py makemigrations
python manage.py migrate

Create a Simple Search Form:

# mysearchapp/forms.py
from django import forms

class SearchForm(forms.Form):
    query = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Search'}))

Create a Search View:

# mysearchapp/views.py
from django.shortcuts import render
from .models import Item
from .forms import SearchForm

def search_view(request):
    query = request.GET.get('query', '')
    results = []

    if query:
        results = Item.objects.filter(name__icontains=query)

    return render(request, 'mysearchapp/search_results.html', {'query': query, 'results': results})

search_results.html

<!-- mysearchapp/templates/mysearchapp/search_results.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Search Results</title>
</head>
<body>
    <h1>Search Results</h1>
    
    <p>Results for '{{ query }}':</p>
    
    {% if results %}
        <ul>
            {% for item in results %}
                <li>{{ item.name }} - {{ item.description }}</li>
            {% endfor %}
        </ul>
    {% else %}
        <p>No results found.</p>
    {% endif %}
</body>
</html>

How can we help?