本文介绍了如何实现Post / Redirect / Get in django分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看法,过滤掉发布搜索表单的结果:

  def profile_advanced_search(request):
args = {}
如果request.method ==POST:
form = AdvancedSearchForm(request.POST)
qs = []
如果form.is_valid():
cd = form.cleaned_data

s_country = cd ['country']
s_province = cd ['province']
s_city = cd ['city']

如果s_country:qs.append(Q(country__icontains = s_country))
如果s_province:qs.append(Q(province__icontains = s_province))
如果s_city:qs.append Q(city__icontains = s_city))



f =无
q中的q:
如果f为无:
f = q

else:f& = q
list = UserProfile.objects.filter(f).order_by(' - created_at')


else:
form = AdvancedSearchForm()
list = UserProfile.objects.all()。order_by(' - created_at')

paginator = Paginator(list,10 )
page = request.GET.get('page')
try:
results = paginator.page(page)
except PageNotAnInteger:
results = paginator。 (1)

除了EmptyPage:
results = paginator.page(paginator.num_pages)

args.update(csrf(request))
args ['form'] = form
args ['results'] = results
return render_to_response('userprofile / advanced_search.html',args,
context_instance = RequestContext(request))

urls.py部分是:

  url(r'^ search / $','userprofile.views.profile_advanced_search'),

模板是:

 < form action = / search /method =post> {%csrf_token%} 

< ul class =list-unsyled>

< li>< h3>国家< / h3>< / li>
< li> {{form.country}}< / li>< br>
< h4>省< / h4>
< li> {{form.province}}< / li>
< h4>城市< / h4>
< li> {{form.city}}< / li>


< / ul>

< input type =submitname =submitvalue =search/>

< / form>
搜索结果:
{%in p in results%}

< div>
< div>
< br>
< strong>< a href =/ profile / {{p.username}}> {{p.username}}< / a>< / strong>
{{p .country}}< br>
{{p.province}}< br>
{{p.city}}< br>

< / div> ;
< / div>
{%endfor%}



< div>
< div class =pagination >
{%if results.has_previous%}
< a href =?page = {{results.previous_page_number}}><< Prev< / a> &b
{%endif%}

{%if results.has_next%}
< a href =?page = {{results.next_page_number}} > Next&g吨;> < / A>
{%endif%}
< / div>
< / div>

< / div>

这些工作适用于第一页,但是为了处理以后的页面,它是,我需要实现Post / Redirect / Get。 / p>

但是,我很难使这样的视图/模板/网址处理GET页面,所有的搜索参数是任意的。所以我感谢一个完整的解决方案。

解决方案

需要 2 视图。第一个用于表单搜索,第二个显示结果。您没有在您的示例代码中以任何方式实施重定向!



urls

  ... 
url(r'^ search / $',
'userprofile.views.profile_advanced_search'),
url(r'^ show /(?P< country> \w +)/(?P< province> \w +)/(?P< site> \w +)/(?P< page> \d + 'userprofile.views.profile_advanced_show'),
...

profile_advanced_search

  def profile_advanced_search(request):
args = {}
if request.method = =POST:
form = AdvancedSearchForm(request.POST)
qs = []
如果form.is_valid():
cd = form.cleaned_data

s_country = cd ['country']
s_province = cd ['province']
s_city = cd ['city']

return HttpResponseRedirect(
反向('userprofile.view
args =(s_country,s_province,s_city,0,))

返回HttpResponseRedirect(
reverse('userprofile.views.profile_advanced_show',
args =('+','+','+',0,)))

profile_advanced_show

  def profile_advanced_show(request,s_country ='',
s_province =' ',s_city ='',page = 0)
f = s_country,s_province和s_city的一些过滤器
list = UserProfile.objects.filter(f).order_by(' - created_at')

paginator = Paginator(list,10)
try:
results = paginator.page(page)
except PageNotAnInteger:
results = paginator.page(1)

除了EmptyPage:
results = paginator.page(paginator.num_pages)

args.update(csrf(request))
form = AdvancedSearchForm(initial = {'s_country':s_country,...})
args ['form'] = form
args ['results'] = results
return render_to_response userprofile / advanced_search.html',args,
context_instance = RequestContext(request))

通知:提交不正确的表单提交。记住,您可以通过GET将参数发送到第二个视图作为键值,而不是路由值。


I have a view that filters out results for a posted search form:

def profile_advanced_search(request):
    args = {}
    if request.method == "POST":
        form = AdvancedSearchForm(request.POST)
        qs=[]
        if form.is_valid():
            cd = form.cleaned_data

            s_country=cd['country']
            s_province=cd['province']
            s_city = cd['city']

            if s_country: qs.append(Q(country__icontains = s_country))    
            if s_province: qs.append( Q(province__icontains=s_province))                
            if s_city: qs.append( Q(city__icontains=s_city))



            f = None
            for q in qs:
                if f is None: 
                    f=q 

                else: f &=q
            list = UserProfile.objects.filter(f).order_by('-created_at') 


    else:
        form = AdvancedSearchForm()
        list = UserProfile.objects.all().order_by('-created_at')

    paginator = Paginator(list,10)            
    page= request.GET.get('page')
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)  

    except EmptyPage:
            results = paginator.page(paginator.num_pages)        

    args.update(csrf(request))    
    args['form'] = form  
    args['results'] = results
    return render_to_response('userprofile/advanced_search.html', args,
                              context_instance=RequestContext(request))  

the urls.py part is:

url(r'^search/$', 'userprofile.views.profile_advanced_search'),

The template is:

  <form action="/search/" method="post">{% csrf_token %}

              <ul class="list-unstyled">

                <li><h3>Country</h3></li>
                <li>{{form.country}}</li><br> 
                <h4>Province</h4>
                <li>{{form.province}}</li>
                  <h4>City</h4>
                <li>{{form.city}}</li>


              </ul>

    <input  type="submit" name="submit"  value="search" />

     </form>
         Search Results:
    {% for p in results %}

                <div">
                      <div>
                          <br>
                           <strong><a href="/profile/{{p.username}}" >{{p.username}}</a></strong>
                             {{p.country}} <br>
                             {{p.province}} <br>
                             {{p.city}} <br>

                         </div>
                      </div>
    {% endfor %}



    <div>
        <div class="pagination">
          {% if results.has_previous %}
              <a href="?page={{ results.previous_page_number }}"> << Prev </a>&nbsp;&nbsp
          {% endif %}

           {% if results.has_next %}
              <a href="?page={{ results.next_page_number }}"> Next >> </a>
          {% endif %}
        </div>
      </div>

    </div>

These work fine for the first page, but to deal with the later pages, it is suggested that I need to implement Post/Redirect/Get .

However I have had difficulty to make such views/template/urls to deal with GET pages regarding that all of the search parameters are arbitrary. So I appreciate a complete solution.

解决方案

Do you need 2 views. First one for form search and second one to show results. You have not implemented redirect in any way in your sample code!

urls

...
url(r'^search/$', 
    'userprofile.views.profile_advanced_search'),
url(r'^show/(?P<country>\w+)/(?P<province>\w+)/(?P<site>\w+)/(?P<page>\d+)',
    'userprofile.views.profile_advanced_show'),
...

profile_advanced_search

def profile_advanced_search(request):
    args = {}
    if request.method == "POST":
        form = AdvancedSearchForm(request.POST)
        qs=[]
        if form.is_valid():
            cd = form.cleaned_data

            s_country=cd['country']
            s_province=cd['province']
            s_city = cd['city']

            return HttpResponseRedirect(
               reverse('userprofile.views.profile_advanced_show', 
                        args=(s_country, s_province, s_city, 0, )))

   return HttpResponseRedirect(
               reverse('userprofile.views.profile_advanced_show', 
                        args=('+', '+', '+', 0, )))

profile_advanced_show

def profile_advanced_show(request, s_country='', 
                          s_province='', s_city='', page=0):
    f = some filters with s_country, s_province and s_city
    list = UserProfile.objects.filter(f).order_by('-created_at') 

    paginator = Paginator(list,10)            
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)  

    except EmptyPage:
        results = paginator.page(paginator.num_pages)        

    args.update(csrf(request))    
    form = AdvancedSearchForm(initial={ 's_country': s_country, ... } )
    args['form'] = form  
    args['results'] = results
    return render_to_response('userprofile/advanced_search.html', args,
                              context_instance=RequestContext(request))        

Notice: improve it for not valid form submissions. Remember you can send parameters to second view via GET as key value instead route values.

这篇关于如何实现Post / Redirect / Get in django分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:46