搜索表单在詹戈与蟒蛇

我正在尝试在我的django网站上添加一个简单的搜索表单。当我点击搜索按钮时,我被重定向到new_search.html页面(应该是这样),但该页面没有显示任何结果。感谢您的帮助!


代码是这样的:


我有一个主页,我把搜索表单放成这样:


<form method="get" action="{% url 'new_search' %}">

      {%csrf_token%}

      <input type="text" name="srh" class= "form-control" placeholder="Search">

      <button type="submit" name="submit">Search</button>

</form>

当用户搜索某些内容时,结果应显示在new_search.html页面中。我在 views.py 中编写的函数是这样的:


def new_search(request):

    if request.method == 'GET':

        srch = request.GET.get('srh')


        if srch:

            sr = Info.objects.filter(Q(band__icontains=srch) | Q(disco__icontains=srch))


            if sr:

                return render(request, 'new_search.html', {'sr':sr})

            else:

                messages.error(request, 'no results')

        else:

            return render(request, 'new_search')


    return render(request, 'new_search.html')

new_search.html页面是这样的:


    <div>

{% if sr %}

  {% for k in sr %}

        <table width="200px">

          <tr><td>Band</td><td>{{k.band}}</td></tr>

          <tr><td>Album</td><td>{{k.disco}}</td></tr>

        </table>

  {%endfor%}

{%endif%}

    </div>

model.py 是这样的:


class Info(models.Model):

    band = models.CharField(max_length=200, help_text="Write Here")

    disco = models.CharField(max_length=200, help_text="Write Here")

    etichetta_p = models.CharField(max_length=200, help_text="Write Here")

    etichetta_d = models.CharField(max_length=200, help_text="Write Here")

    matrice = models.CharField(max_length=200, help_text="Write Here")

    anno = models.PositiveIntegerField(default=0)

    cover = models.ImageField(upload_to='images/')


    def __str__(self):

        return self.band

urls.py


urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('search.urls')),

    path('accounts/', include('django.contrib.auth.urls')),



守着星空守着你
浏览 59回答 1
1回答

哔哔one

在我看来,你应该在类视图中处理方法,因为你正在使用一个,例如:POSTclass new_searchView(TemplateView):&nbsp; &nbsp; template_name = "new_search.html"&nbsp; &nbsp; def post(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; print('FORM POSTED WITH {}'.format(request.POST['srh']))&nbsp; &nbsp; &nbsp; &nbsp; return render(self.request, 'new_search.html')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python