Django通用列表视图与多个查询搜索

huangapple go评论77阅读模式
英文:

Django generic List View with multiple query search

问题

models.py

from django.db import models
from django.core.validators import RegexValidator

class Product(models.Model):
    num = RegexValidator(r'^[0-9a-zA-Z]*$')
    title = models.CharField(max_length=100)
    embed_id = models.CharField(max_length=15, validators=[num])
    description = models.TextField(null=True, blank=True)

forms.py

from django import forms

class ProductSearchForm(forms.Form):
    title = forms.CharField(required=False)
    embed_id = forms.CharField(required=False)
    description = forms.CharField(required=False)

views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm

class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = 'pages/product/list_products.html'

    def get_queryset(self):
        queryset = super().get_queryset()
        form = self.form_class(self.request.GET)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            embed_id = form.cleaned_data.get('embed_id')
            description = form.cleaned_data.get('description')
            if title:
                queryset = queryset.filter(title__icontains=title)
            if embed_id:
                queryset = queryset.filter(embed_id__icontains=embed_id)
            if description:
                queryset = queryset.filter(description__icontains=description)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = self.form_class(self.request.GET)
        return context

product_search.html

<form method="get" action="{% url 'product_list' %}">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% if object_list %}
<ul>
{% for product in object_list %}
<li>{{ product.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No product found.</p>
{% endif %}

I've corrected the code formatting and removed HTML encoding for better readability.

英文:

Hello I'm working with class based views in Django and I want to create a search form for users to find their own favourite products in my app with multiple filters and excludes but I couldn't do it. my code is here if anyone can modify it to make it right please help me out :

models.py

from django.db.models import models
from django.core.validators import RegexValidators


class Product(models.Model):
    num=RegexValidators(r&#39;^[0-9a-zA-Z]*$&#39;)
    title = models.CharField(max_length=100)
    embed_id = models.CharField(max_length=15, validators=[num])
    description = models.TextField(null=True, blank=True)

forms.py

from django import forms


class ProductSearchForm(forms.Form):
    title = forms.CharField(required=False)
    embed_id = forms.CharField(required=False)
    description = forms.CharField(required=False)

views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm


class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = &#39;pages/product/list_products.html&#39;

    def get_queryset(self):
       queryset = super().get_queryset()
       form = self.form_class(self.request.GET)
       if form.is_valid():
           title = form.cleaned_data.get(&#39;title&#39;)
           embed_id = form.cleaned_data.get(&#39;embed_id&#39;)
           description = form.cleaned_data.get(&#39;description&#39;)
           if title:
              queryset = queryset.filter(title__icontains=title)
           if embed_id:
              queryset = queryset.filter(embed_id__icontains=embed_id)
           if description:
              queryset = queryset.filter(description__icontains=description)
           return queryset

   def get_context_data(self, [**kwargs):
      context = super().get_context_data(self, **kwargs):
      context[&#39;form&#39;] = self.form_class(self.request.GET)
      return context

product_search.html

&lt;form method=&quot;get&quot; action=&quot;{% url &#39;product_list&#39; %}&quot;&gt;
{{ form.as_p }}
&lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;
&lt;/form&gt;
{% if object_list %}
&lt;ul&gt;
{% for product in object_list %}
&lt;li&gt;{{ product.title }}&lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
{% else %}
&lt;p&gt;No product found.&lt;/p&gt;
{% endif %}

I know how to handle this in Function based views, but I want to create its generic.listview.

答案1

得分: 1

我尝试使用你的代码,但无法运行。

这是我的方法:

views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm

class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = 'product.html'
    context_object_name = 'products'
    
    def get_queryset(self):
        queryset = super().get_queryset()
        form = self.form_class(self.request.GET)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            embed_id = form.cleaned_data.get('embed_id')
            description = form.cleaned_data.get('description')
            if title:
                queryset = queryset.filter(title__icontains=title)
            if embed_id:
                queryset = queryset.filter(embed_id__icontains=embed_id)
            if description:
                queryset = queryset.filter(description__icontains=description)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = self.form_class(self.request.GET)
        return context

所有数据

data

搜索数据

results

英文:

I tried using your code cannot run.

Here is my way:

views.py

from django.views.generic import ListView
from .models import Product
from .forms import ProductSearchForm


class ProductListView(ListView):
    model = Product
    form_class = ProductSearchForm
    template_name = &#39;product.html&#39;
    context_object_name = &#39;products&#39;
    
    def get_queryset(self):
        queryset = super().get_queryset()
        form = self.form_class(self.request.GET)
        if form.is_valid():
            title = form.cleaned_data.get(&#39;title&#39;)
            embed_id = form.cleaned_data.get(&#39;embed_id&#39;)
            description = form.cleaned_data.get(&#39;description&#39;)
            if title:
                queryset = queryset.filter(title__icontains=title)
            if embed_id:
                queryset = queryset.filter(embed_id__icontains=embed_id)
            if description:
                queryset = queryset.filter(description__icontains=description)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context[&#39;form&#39;] = self.form_class(self.request.GET)
        return context

all data

data

search data

results

huangapple
  • 本文由 发表于 2023年6月19日 15:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定