Django – 如何重定向回搜索页面并包括查询条件?

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

Django - How to redirect back to search page and include query terms?

问题

我的页面/视图结构如下:

index.html => search_results.html => object_details.html,
在object_details.html中,用户可以进行POST请求。

我尝试在POST请求后重定向回search_results.html,同时保留两个查询字符串。

搜索结果的URL如下,并可以包含一个或两个查询:

www.example.com/search-results/?search_post=xxxxx&search_author=xxxxx

我能够获得的最接近所需的方式是使用以下代码:

return redirect(reverse('search-results') + '?' + 'search_post={{search_post}}'+'&'+'search_author={{search_author}}')

然而,这实际上会在search_results.html的搜索表单的两个字段中显示"{{search_post}}"和"{{search_author}}",并返回以下URL:

www.example.com/search-results/?search_post=%7B%7Bsearch_post%7D&search_author=%7B%7Bsearch_author%7D%7D

另外,我的search_results视图包括以下内容:

search_post = request.GET.get('search_post')

search_author = request.GET.get('search_author')

我该如何实现这一目标?我尝试使用类似问题的答案,但仍然没有弄清楚。
谢谢!

英文:

My pages/views are structured as follows:

index.html => search_results.html => object_details.html,
in which user can make a POST request in object_details.html.

I am trying to redirect back to search_results.html after the POST request, but also keep both query strings.

The url of search results shows as follows, and can have 1 or both queries made:

www.example.com/search-results/?search_post=xxxxx&search_author=xxxxx

The closest I am able to get what I want is using:

return redirect(reverse('search-results') + '?' + 'search_post={{search_post}}'+'&'+'search_author={{search_author}}')

however this would actually show "{{search_post}}" and "{{search_author}}" in each of the 2 fields of the search form in search_results.html,
and would return the url:

www.example.com/search-results/?search_post=%7B%7Bsearch_post%7D&search_author=%7B%7Bsearch_author%7D%7D

Also, my search_results view has the following:

search_post = request.GET.get('search_post')

search_author = request.GET.get('search_author')

How can I do this? Tried using answers for similar questions but yet to figure it out.
Thank you

答案1

得分: 1

你的引号使用错误。你不能使用与Django模板相同的语法。尝试使用f-string:

return redirect(reverse('search-results') + f"?search_post={search_post}&search_author={search_author}")

关于字符串的文档:https://peps.python.org/pep-0498/

在你的回答后,我重构了你的视图。实际上,你可以在表单处理的每个步骤中重复使用results进行下一轮过滤。我认为你的连锁elif不太好,可能会导致错误。

def search_results(request, *args, **kwargs):

    search_post = request.GET.get('search_post', '')
    search_author = request.GET.get('search_author', '')

    results = Post.objects.all()
    if search_author != '':
        results = results.filter(city__icontains=search_author.strip())
    
    if search_post != '':
        results = results.filter(post__icontains=search_post.strip())

    context = {
        'results': results,
        'search_post': search_post,
        'search_author': search_author,
    }

    return render(request, 'search_results.html', context)
英文:

You just make an error with quotes. You cannot use same syntax as django template. Try using f-string:

return redirect(reverse('search-results') + f"?search_post={search_post}&search_author={search_author}")

Documentation about string: https://peps.python.org/pep-0498/

Ok after your answer, I made a refactoring your view. You can reuse the results for the next filtering at each step of your form processing in fact. And your, I think, your chaining elif was not good and make error.

def search_results(request, *args, **kwargs):

    search_post = request.GET.get('search_post', '')
    search_author = request.GET.get('search_author', '')

    results = Post.objects.all()
    if search_author != '':
        results = results.filter(city__icontains=search_author.strip())
    
    if search_post != '':
        results = results.filter(post__icontains=search_post.strip())

    context = {
        'results': results,
        'search_post': search_post,
        'search_author': search_author,
    }

    return render(request, 'search_results.html', context)

答案2

得分: 0

views.py

def index(request):
    return render(request, 'index.html')

def search_results(request, *args, **kwargs):

    search_post = request.GET.get('search_post')
    search_author = request.GET.get('search_author')

    if search_author and not search_post:
        results = Post.objects.distinct().filter(
            (Q(city__icontains=search_author.strip())))
    
    elif search_post and not search_author:
        results = Post.objects.distinct().filter(
            (Q_post__icontains=search_post.strip()))
    
    elif search_post and search_author:
        results = Post.objects.distinct().filter(
            (Q_post__icontains=search_post.strip())
            )
            .filter(
            (Q(city__icontains=search_author.strip())
            )
            )
    
    elif search_post and search_author == None:
        results = Post.objects.all().distinct()
        return render(request, 'search_results.html', {'results':results, 'search_post':search_post, 'search_author':search_author})
    
    else:
        results = Post.objects.all().distinct()

    return render(request, 'search_results.html', {'results':results, 'search_post':search_post, 'search_author':search_author})

def post_details(request, pk):

    post = Post.objects.get(pk=pk)
    post_owner = post.owner
    search_post = request.GET.get('search_post')
    search_author = request.GET.get('search_author')

    if request.user.is_authenticated:
        saved = Submission.objects.filter(post=post, owner=request.user)
        if saved and request.method == 'POST':
            return render(request, 'post_details.html', {'post':post, 'saved':saved})

        if request.method == 'POST':
            instance = Submission(post=post, post_owner=post_owner,owner=request.user)
            instance.save()
            return redirect('post-details', pk=post.id)

    else:
        return render(request, 'post_details.html', {'post':post})

    return render(request, 'post_details.html', {'post':post, 'saved':saved})
英文:

views.py

def index(request):
return render(request, 'index.html')
def search_results(request, *args, **kwargs):
search_post = request.GET.get('search_post')
search_author = request.GET.get('search_author')
if search_author and not search_post:
results = Post.objects.distinct().filter(
(Q(city__icontains=search_author.strip())))
elif search_post and not search_author:
results = Post.objects.distinct().filter(
(Q_post__icontains=search_post.strip()))
elif search_post and search_author:
results = Post.objects.distinct().filter(
(Q_post__icontains=search_post.strip())
)
.filter(
(Q(city__icontains=search_author.strip())
)
)
elif search_post and search_author == None:
results = Post.objects.all().distinct()
return render(request, 'search_results.html', {'results':results, 'search_post':search_post, 'search_author':search_author})
else:
results = Post.objects.all().distinct()
return render(request, 'search_results.html', {'results':results, 'search_post':search_post, 'search_author':search_author})
def post_details(request, pk):
post = Post.objects.get(pk=pk)
post_owner = post.owner
search_post = request.GET.get('search_post')
search_author = request.GET.get('search_author')
if request.user.is_authenticated:
saved = Submission.objects.filter(post=post, owner=request.user)
if saved and request.method == 'POST':
return render (request, 'post_details.html', {'post':post, 'saved':saved})
if request.method == 'POST':
instance = Submission(post=post, post_owner=post_owner,owner=request.user)
instance.save()
return redirect('post-details', pk=post.id)
else:
return render (request, 'post_details.html', {'post':post})
return render (request, 'post_details.html', {'post':post, 'saved':saved})

huangapple
  • 本文由 发表于 2023年3月7日 13:55:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658458.html
匿名

发表评论

匿名网友

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

确定