查询字符串参数在Django

时间:2015-05-17 17:46:50

标签: python django

我正在使用Django构建一个简单的照片组合网站。我的应用程序"在这个项目中称为" photoViewer"。 " photoViewer / photos /"显示照片列表,每张照片的缩略图,日期和标题。我想按日期添加订单,并按标题功能按此顺序排序。

为此,我添加了几个按钮,我想将用户重定向回照片列表视图,但在网址上附加了一个字符串:" date_desc&#34 ;或" title_desc" (即" photoViewer / photos / order_desc"或" photoViewer / photos / title_desc")。然后,我又为我的" photoViewer / urls.py"添加了另一个网址模式。尝试为过滤器类型捕获此附加字符串。我希望将此字符串从我的urls.py传递到views.py中的photoIndex类视图。类视图将检查此过滤器类型字符串并执行正确的逻辑,以便相应地按日期或标题排序。

我的问题:1。我如何参考并检查这个"捕获"过滤器类型字符串附加到views.py中的photoIndexView()类中的照片列表视图URL。 2.如何将此字符串传递给我的photoIndex template.html(或者这甚至不是必需的,因为业务逻辑应该在views.py而不是模板文件中)

photoViewer / urls.py:

from django.conf.urls import patterns, include, url
from photoViewer import views

# map url to view using a URLconf
urlpatterns = patterns('',
   url(r'^$', views.PhotoIndexView.as_view(), name='photo_index'),
   url(r'^about/', views.PhotoViewerAboutView.as_view()),

   #My attempt below to capture any string w/o number as last param
   #route for photo list view w/ potential filter type string passed
   url(r'^photos/(?P<filter_type>[^\d+]*)$', views.PhotoIndexView.as_view(), name='photo_index'),

   #my route for photo detail view
   url(r'^photos/(?P<pk>\d+)/$', views.PhotoDetailView.as_view(), name='photo_detail'),

   ...
)

photoViewer / views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from photoViewer.models import Photo, Album


class PhotoViewerAboutView (generic.TemplateView):
     template_name = 'photoViewer/photoViewer_about.html'


class PhotoIndexView (generic.ListView):
     template_name = 'photoViewer/photo_index.html'
     context_object_name = 'latest_photo_list'

     def get_queryset(self):
          return Photo.objects.order_by('-date_taken')[:5]
...

photoViewer /模板/ photoViewer / photo_index.html

{% extends 'base.html' %}

{% block title %}Photo Index{% endblock %}
{% block contents %}

<h1>Photo Index</h1>
<br>

<button id="sortBtn" type="button" class="btn btn-default">
  Date Taken: <span class="glyphicon glyphicon-sort" aria-hidden="true">  </span>
</button>

<br />
{% if latest_photo_list %}
    {% for photo in latest_photo_list %}
    <div class="container-fluid">
        <div class="row">
          <!-- Total Column width of 12 -->
          <div id = "per-pic" class="col-xs-12 col-md-6">
              <a href="{% url 'photoViewer:photo_detail' photo.id %}">
                <img src="/media/{{ photo.photo_img }}" class="img-thumbnail"  width="100%" height="100%" />
              </a>
              <li>
               <span class="label label-primary">{{ photo.photo_title }}</span>
               <span class="label label-info">{{ photo.date_taken }}</span>
              </li>
          </div>
        </div>
    </div>
    <br>
    {% endfor %}
{% else %}
<p>No Photos are available.</p>
{% endif %}
<script type="text/javascript">
    var sortButton = document.getElementById("sortBtn");
    sortButton.onclick = function () {
        //Append Filter type as string to URL?
        location.href = "date_asc";
    };
 //  sortButton.addEventListener("click", redirectSortBtn, false);
</script>
{% endblock %}

photoViewer /模板/ photoViewer / base.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>{% block title %}My amazing site{% endblock %}</title>

    <!-- Bootstrap core CSS -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">


    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="../../assets/js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

       <!--Personal Custom CSS-->
      <link href="/static/css/personal.css" rel="stylesheet">

  </head>

  <body>
    <nav class="navbar">
      <div class="container">
            <ul class="pager" id = "nav_bar">
              <li><a href="/photoViewer/about">About</a></li>
              <li><a href="/photoViewer/photos/">Stream</a></li>
            </ul>

        </div><!--/.navbar-collapse -->
    </nav>


    <div class="jumbotron">
    {% block contents %}

    {% endblock %}
    </div>
      <hr>

      <footer>
        <p>&copy; Company 2014</p>
      </footer>
    </div> <!-- /container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
   <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="/static/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以使用$myqry = "Update users SET username = '". $name."', email = '".$email."' , address = '".$address."', contactinfo = '".$contactinfo."' WHERE id = ".$id."; echo($myqry; $queryreg = mysql_query($myqry); if ..... self.args获取网址参数。更改查询集覆盖self.kwargs。将其他变量传递给模板覆盖self.get_queryset。 例如:

<强> views.py

self.get_context_data

您可以修改class PhotoIndexView (generic.ListView): template_name = 'photoViewer/photo_index.html' context_object_name = 'latest_photo_list' def get_queryset(self): filter_type = self.kwargs['filter_type'] if filter_type == 'date_desc': return Photo.objects.order_by('-date_taken')[:5] elif == 'title_desc': return Photo.objects.order_by('-title')[:5] else: # default ordering return Photo.objects.all()[:5] def get_context_data(self, **kwargs): context = super(PhotoIndexView, self).get_context_data(**kwargs) context['filter_type'] = self.kwargs['filter_type'] return context 以输入less,类似这样的

get_queryset

另外,我建议更改get_queryset(self): filter_type = self.kwargs['filter_type'] qs = Photo.objects.all() if filter_type == 'data_desc': qs = qs.order_by('-data_taken') elif filter_type == 'title_decs': qs = qs.order_by('-title') return qs[:5] ,类似这样的

<强> urls.py

urls.py

变为

   url(r'^photos/(?P<filter_type>[^\d+]*)$', views.PhotoIndexView.as_view(), name='photo_index'),