R
R
rusyska550112021-03-14 23:53:14
Django
rusyska55011, 2021-03-14 23:53:14

django 3 post search not implemented? Where is the mistake?

models.py

class News(models.Model):
    title = models.CharField(max_length = 30, verbose_name = 'Заголовок')
    content = models.TextField(verbose_name = 'Контент')
    picture = models.ImageField(upload_to = 'pictures/News', default = 'null', null = True, blank = True, verbose_name = 'Картинка')
    published = models.DateField(auto_now_add = True, db_index = True, verbose_name = 'Дата')
    rubric = models.ForeignKey('Rubric', default = 'Без рубрики', on_delete = models.PROTECT, verbose_name = 'Рубрика')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Новости'
        verbose_name = 'Новости'
        ordering = ['-published']


views.py:
class Search(ListView):
    paginate_by = 3

    def get_queryset(self):
        return News.objects.filter(title__icontains = self.request.GET.get("q"))

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["q"] = self.request.GET.get("q")
        return context


urls.py
urlpatterns = [
    ...  
    path('search/', views.Search.as_view(), name = 'search') 

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


The form
<form method="get", action = "{% url 'search' %}">

      <input type="search" placeholder="Введите название статьи" name="search" class="form-control">
      <button class = "btn btn-success" type = "sumbit"> Отправить </button>

    </form>


As a result, this error:
604e778794a46950768073.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-03-15
@rusyska55011

The search parameter in your form is called search: <input type="search" ... name="search" ...>, and in the view - q:

return News.objects.filter(title__icontains = self.request.GET.get("q"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question