1

I'm developing Django app.

I want to render variable "q_word" to the template from this views.py

class DbList(ListView):
    model = TestEu
    paginate_by = 10

    def get_queryset(self):
        q_word = self.request.GET.get('query')

        if q_word:
            sql = 'select * from test_eu'
            sql += " where eng_discription ~ '.*" + q_word +".*'" 
            object_list = TestEu.objects.raw(sql)
            return object_list

Since "get_queryset" function apply "self" as first argument

def get_queryset(self):

I don't know how to apply below code to render.

return render(request, 'detail.html', {'q_word': q_word})
daylyroppo
  • 67
  • 4

1 Answers1

0

This will not be passwed a q_word to the template. If you need access, you can however use:

{{ view.request.GET.query }}

or you can pass it to the context:

class DbList(ListView):
    model = TestEu
    paginate_by = 10

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(
            *args,
            q_word=self.request.GET.get('query'),
            **kwargs
        )

    def get_queryset(self):
        q_word = self.request.GET.get('query')

        if q_word:
            sql = 'select * from test_eu'
            sql += " where eng_discription ~ '.*" + q_word +".*'" 
            object_list = TestEu.objects.raw(sql)
            return object_list

Note that the query you make is vulnerable for SQL injection [wiki]. This is one of the (many) reasons why using the Django ORM is better.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555