【问题标题】:How Can I execute search function after click on specific category name?单击特定类别名称后如何执行搜索功能?
【发布时间】:2021-07-20 03:45:35
【问题描述】:

我在主页上的Anchor tags 中有一些书籍类别名称。如果用户单击特定类别,我想向他们展示该类别的所有书籍。但我想不出将类别名称从 Anchor 标记通过url.py 传递给views.py,然后执行搜索功能
home.html

<ul class="book-catagory">
    <li class="list-item">
        <a href="{% url 'home' %}">Philosophy</a>
    </li>
    <li class="list-item">
        <a href="{% url 'home' %}">Litereture</a>
    </li>
    <li class="list-item">
        <a href="{% url 'home' %}">Computer Science</a>
    </li>
    <li class="list-item">
        <a href="{% url 'home' %}">Electrical</a>
    </li>
</ul>

path in url.py

path('',views.home, name='home')

views.py

def home(request):
    if request.method == 'POST':
        searchName = request.POST.get('searchBook')
        if not searchName :
             searchName = ""
        
        context={
            'data': Book.objects.filter(bookname__contains=searchName)
        }
        return render(request, 'library_site/home.html',context)
    else:
        context={
            'data': Book.objects.all()
        }           
    return render(request, 'library_site/home.html',context)

【问题讨论】:

标签: django django-models django-views django-templates django-urls


【解决方案1】:

views.py

def Book1(请求): 类别=['1']

books= Product.objects.filter(category=category)

context = {'books':books}
return render(request, 'store/store.html', context)

urls.py

urlpatterns = [

path('book1/', views.Book1, name='book1')

]

模型.py 从多选字段导入多选字段

类书(models.Model): MY_CHOICES = ((1, 'book1'), (2, 'book2'),

          )

category = MultiSelectField(choices=MY_CHOICES,
                     max_choices=4,
                     max_length=30,null=True,blank=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 2015-06-05
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2021-12-31
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多