Django redirect after search using a querysetHow to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Does Django scale?Getting the SQL from a Django QuerySetRedirect from an HTML pagedifferentiate null=True, blank=True in djangoHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?Display a ListView inside a TabView with DjangoDjango how to save time to the forms?Django problem with having slug in my url while using a class

Did depressed people far more accurately estimate how many monsters they killed in a video game?

This LM317 diagram doesn't make any sense to me

Is "wissen" the only verb in German to have an irregular present tense?

Why does Trump want a citizenship question on the census?

Why did Old English lose both thorn and eth?

Interpretation of non-significant results as "trends"

What are the consequences for a developed nation to not accept any refugees?

What was the nature of the known bugs in the Space Shuttle software?

What do you call a situation where you have choices but no good choice?

Sense of humor in your sci-fi stories

Is homosexuality or bisexuality allowed for women?

Why is a mixture of two normally distributed variables only bimodal if their means differ by at least two times the common standard deviation?

Matrices with shadows

Why am I getting unevenly-spread results when using $RANDOM?

What term do you use for someone who acts impulsively?

As a supervisor, what feedback would you expect from a PhD who quits?

Gaining Proficiency in Vehicles (water)

What is the meaning of "prairie-dog" in this sentence?

Can one block with a protection from color creature?

Why won't the U.S. sign a peace treaty with North Korea?

How should I ask for a "pint" in countries that use metric?

Draw a diagram with rectangles

A ring of generalized power series

How do I separate enchants from items?



Django redirect after search using a queryset


How to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Does Django scale?Getting the SQL from a Django QuerySetRedirect from an HTML pagedifferentiate null=True, blank=True in djangoHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?Display a ListView inside a TabView with DjangoDjango how to save time to the forms?Django problem with having slug in my url while using a class






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















When I click search on the homepage, I want it to take that query set e.g (http://127.0.0.1:8000/?q=car) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working.



Views:



class IndexView(ListView):
model = Post
# queryset = Post.objects.filter(live=True)
template_name = "public/index.html"

def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title__icontains=query)
return redirect(reverse('search-view'), queryset)

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['queryset'] = self.get_queryset()
context['category'] = Category.objects.all()
return context


URLS:



urlpatterns = [
path('', views.IndexView.as_view(), name="index-view"),

path('post/create/', views.PostCreateView.as_view(), name="post-create"),
path('post/<slug>/update/', views.PostUpdateView.as_view(), name="post-update"),
path('post/<slug>/', views.PostDetailView.as_view(), name="post-detail"),

path('category/', views.CategoryView.as_view(), name="category"),
path('category/<int:pk>/', views.CategoryDetailView.as_view(), name="category-detail"),

path('search/', views.SearchListView.as_view(), name="search-view")
]


I have tried doing it using a redirect and reverse but it is not working at all, it is actually giving me an error for using slice on a forloop that is using queryset. 'slice' object has no attribute 'lower'



I have 2 templates/views. When I click search on the homepage, I want it to carry on over to the search view and then run the search query on there.



Thanks.










share|improve this question
























  • "I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

    – Johan
    Mar 25 at 22:34












  • @Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

    – Max Loyd
    Mar 25 at 22:36











  • No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

    – Johan
    Mar 25 at 22:38












  • Or possibly redirect(reverse('search-view'), args=(queryset))

    – Johan
    Mar 25 at 22:43











  • I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

    – Max Loyd
    Mar 25 at 22:48

















0















When I click search on the homepage, I want it to take that query set e.g (http://127.0.0.1:8000/?q=car) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working.



Views:



class IndexView(ListView):
model = Post
# queryset = Post.objects.filter(live=True)
template_name = "public/index.html"

def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title__icontains=query)
return redirect(reverse('search-view'), queryset)

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['queryset'] = self.get_queryset()
context['category'] = Category.objects.all()
return context


URLS:



urlpatterns = [
path('', views.IndexView.as_view(), name="index-view"),

path('post/create/', views.PostCreateView.as_view(), name="post-create"),
path('post/<slug>/update/', views.PostUpdateView.as_view(), name="post-update"),
path('post/<slug>/', views.PostDetailView.as_view(), name="post-detail"),

path('category/', views.CategoryView.as_view(), name="category"),
path('category/<int:pk>/', views.CategoryDetailView.as_view(), name="category-detail"),

path('search/', views.SearchListView.as_view(), name="search-view")
]


I have tried doing it using a redirect and reverse but it is not working at all, it is actually giving me an error for using slice on a forloop that is using queryset. 'slice' object has no attribute 'lower'



I have 2 templates/views. When I click search on the homepage, I want it to carry on over to the search view and then run the search query on there.



Thanks.










share|improve this question
























  • "I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

    – Johan
    Mar 25 at 22:34












  • @Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

    – Max Loyd
    Mar 25 at 22:36











  • No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

    – Johan
    Mar 25 at 22:38












  • Or possibly redirect(reverse('search-view'), args=(queryset))

    – Johan
    Mar 25 at 22:43











  • I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

    – Max Loyd
    Mar 25 at 22:48













0












0








0








When I click search on the homepage, I want it to take that query set e.g (http://127.0.0.1:8000/?q=car) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working.



Views:



class IndexView(ListView):
model = Post
# queryset = Post.objects.filter(live=True)
template_name = "public/index.html"

def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title__icontains=query)
return redirect(reverse('search-view'), queryset)

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['queryset'] = self.get_queryset()
context['category'] = Category.objects.all()
return context


URLS:



urlpatterns = [
path('', views.IndexView.as_view(), name="index-view"),

path('post/create/', views.PostCreateView.as_view(), name="post-create"),
path('post/<slug>/update/', views.PostUpdateView.as_view(), name="post-update"),
path('post/<slug>/', views.PostDetailView.as_view(), name="post-detail"),

path('category/', views.CategoryView.as_view(), name="category"),
path('category/<int:pk>/', views.CategoryDetailView.as_view(), name="category-detail"),

path('search/', views.SearchListView.as_view(), name="search-view")
]


I have tried doing it using a redirect and reverse but it is not working at all, it is actually giving me an error for using slice on a forloop that is using queryset. 'slice' object has no attribute 'lower'



I have 2 templates/views. When I click search on the homepage, I want it to carry on over to the search view and then run the search query on there.



Thanks.










share|improve this question
















When I click search on the homepage, I want it to take that query set e.g (http://127.0.0.1:8000/?q=car) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working.



Views:



class IndexView(ListView):
model = Post
# queryset = Post.objects.filter(live=True)
template_name = "public/index.html"

def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title__icontains=query)
return redirect(reverse('search-view'), queryset)

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['queryset'] = self.get_queryset()
context['category'] = Category.objects.all()
return context


URLS:



urlpatterns = [
path('', views.IndexView.as_view(), name="index-view"),

path('post/create/', views.PostCreateView.as_view(), name="post-create"),
path('post/<slug>/update/', views.PostUpdateView.as_view(), name="post-update"),
path('post/<slug>/', views.PostDetailView.as_view(), name="post-detail"),

path('category/', views.CategoryView.as_view(), name="category"),
path('category/<int:pk>/', views.CategoryDetailView.as_view(), name="category-detail"),

path('search/', views.SearchListView.as_view(), name="search-view")
]


I have tried doing it using a redirect and reverse but it is not working at all, it is actually giving me an error for using slice on a forloop that is using queryset. 'slice' object has no attribute 'lower'



I have 2 templates/views. When I click search on the homepage, I want it to carry on over to the search view and then run the search query on there.



Thanks.







python html django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 22:36







Max Loyd

















asked Mar 25 at 22:31









Max LoydMax Loyd

1001 silver badge11 bronze badges




1001 silver badge11 bronze badges












  • "I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

    – Johan
    Mar 25 at 22:34












  • @Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

    – Max Loyd
    Mar 25 at 22:36











  • No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

    – Johan
    Mar 25 at 22:38












  • Or possibly redirect(reverse('search-view'), args=(queryset))

    – Johan
    Mar 25 at 22:43











  • I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

    – Max Loyd
    Mar 25 at 22:48

















  • "I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

    – Johan
    Mar 25 at 22:34












  • @Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

    – Max Loyd
    Mar 25 at 22:36











  • No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

    – Johan
    Mar 25 at 22:38












  • Or possibly redirect(reverse('search-view'), args=(queryset))

    – Johan
    Mar 25 at 22:43











  • I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

    – Max Loyd
    Mar 25 at 22:48
















"I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

– Johan
Mar 25 at 22:34






"I have tried doing it using a redirect and reverse but it is not working at all." Can you specify what is not working?

– Johan
Mar 25 at 22:34














@Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

– Max Loyd
Mar 25 at 22:36





@Johan Ah yes sorry my fault. So when I load the IndexView, it gives me an error about using slice. Now I am using slice in a forloop on the IndexView template.

– Max Loyd
Mar 25 at 22:36













No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

– Johan
Mar 25 at 22:38






No worries. I believe you need to use a named parameter in the redirect function, basically like redirect(reverse('search-view'), queryset=queryset) and then handle the argument in the SearchListView

– Johan
Mar 25 at 22:38














Or possibly redirect(reverse('search-view'), args=(queryset))

– Johan
Mar 25 at 22:43





Or possibly redirect(reverse('search-view'), args=(queryset))

– Johan
Mar 25 at 22:43













I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

– Max Loyd
Mar 25 at 22:48





I have added queryset=queryset but not sure how to handle the argument in the SearchListView, sorry I am fairly new to Django.

– Max Loyd
Mar 25 at 22:48












1 Answer
1






active

oldest

votes


















0














I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the IndexView that is meant for the SearchListView.



From the information that's available right now (without the SearchListView) I'd say you could do a redirect and pass the parameter onto the query url and let the view in SearchListView decide what to do with the information:



def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
# Fetch the url for the search-view
base_url = reverse('search-view')
# Make the search query url encoded
query_string = urlencode('q': query)
# Tie it together with the url
url = '?'.format(base_url, query_string)
# Fire away
return redirect(url)
return redirect(reverse('search-view'), queryset)


Source:
Some code taken from The Ultimate Guide to Django Redirects by Daniel Hepper






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347336%2fdjango-redirect-after-search-using-a-queryset%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the IndexView that is meant for the SearchListView.



    From the information that's available right now (without the SearchListView) I'd say you could do a redirect and pass the parameter onto the query url and let the view in SearchListView decide what to do with the information:



    def get_queryset(self):
    queryset = super().get_queryset().filter(live=True)
    query = self.request.GET.get("q")
    if query:
    # Fetch the url for the search-view
    base_url = reverse('search-view')
    # Make the search query url encoded
    query_string = urlencode('q': query)
    # Tie it together with the url
    url = '?'.format(base_url, query_string)
    # Fire away
    return redirect(url)
    return redirect(reverse('search-view'), queryset)


    Source:
    Some code taken from The Ultimate Guide to Django Redirects by Daniel Hepper






    share|improve this answer



























      0














      I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the IndexView that is meant for the SearchListView.



      From the information that's available right now (without the SearchListView) I'd say you could do a redirect and pass the parameter onto the query url and let the view in SearchListView decide what to do with the information:



      def get_queryset(self):
      queryset = super().get_queryset().filter(live=True)
      query = self.request.GET.get("q")
      if query:
      # Fetch the url for the search-view
      base_url = reverse('search-view')
      # Make the search query url encoded
      query_string = urlencode('q': query)
      # Tie it together with the url
      url = '?'.format(base_url, query_string)
      # Fire away
      return redirect(url)
      return redirect(reverse('search-view'), queryset)


      Source:
      Some code taken from The Ultimate Guide to Django Redirects by Daniel Hepper






      share|improve this answer

























        0












        0








        0







        I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the IndexView that is meant for the SearchListView.



        From the information that's available right now (without the SearchListView) I'd say you could do a redirect and pass the parameter onto the query url and let the view in SearchListView decide what to do with the information:



        def get_queryset(self):
        queryset = super().get_queryset().filter(live=True)
        query = self.request.GET.get("q")
        if query:
        # Fetch the url for the search-view
        base_url = reverse('search-view')
        # Make the search query url encoded
        query_string = urlencode('q': query)
        # Tie it together with the url
        url = '?'.format(base_url, query_string)
        # Fire away
        return redirect(url)
        return redirect(reverse('search-view'), queryset)


        Source:
        Some code taken from The Ultimate Guide to Django Redirects by Daniel Hepper






        share|improve this answer













        I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the IndexView that is meant for the SearchListView.



        From the information that's available right now (without the SearchListView) I'd say you could do a redirect and pass the parameter onto the query url and let the view in SearchListView decide what to do with the information:



        def get_queryset(self):
        queryset = super().get_queryset().filter(live=True)
        query = self.request.GET.get("q")
        if query:
        # Fetch the url for the search-view
        base_url = reverse('search-view')
        # Make the search query url encoded
        query_string = urlencode('q': query)
        # Tie it together with the url
        url = '?'.format(base_url, query_string)
        # Fire away
        return redirect(url)
        return redirect(reverse('search-view'), queryset)


        Source:
        Some code taken from The Ultimate Guide to Django Redirects by Daniel Hepper







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 23:05









        JohanJohan

        2,6081 gold badge7 silver badges19 bronze badges




        2,6081 gold badge7 silver badges19 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347336%2fdjango-redirect-after-search-using-a-queryset%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현