Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在url.py、views.py和<;之间传递查询字符串参数;模板文件>;。Django中的html_Python_Django - Fatal编程技术网

Python 在url.py、views.py和<;之间传递查询字符串参数;模板文件>;。Django中的html

Python 在url.py、views.py和<;之间传递查询字符串参数;模板文件>;。Django中的html,python,django,Python,Django,我正在使用Django构建一个简单的照片组合网站。我在这个项目中的“应用程序”叫做“photoViewer”。“photoViewer/photos/”显示照片列表,其中包含每张照片的缩略图、日期和标题。我想在此视图中添加“按日期排序”和“按标题排序”功能 为此,我添加了几个按钮,并考虑将用户重定向回照片列表视图,但在url后面附加了一个字符串:“date_desc”或“title_desc”(即“photoViewer/photos/order_desc”或“photoViewer/photo

我正在使用Django构建一个简单的照片组合网站。我在这个项目中的“应用程序”叫做“photoViewer”。“photoViewer/photos/”显示照片列表,其中包含每张照片的缩略图、日期和标题。我想在此视图中添加“按日期排序”和“按标题排序”功能

为此,我添加了几个按钮,并考虑将用户重定向回照片列表视图,但在url后面附加了一个字符串:“date_desc”或“title_desc”(即“photoViewer/photos/order_desc”或“photoViewer/photos/title_desc”)。然后,我将另一个url模式添加到我的“photoViewer/url.py”中,该模式尝试捕获过滤器类型的额外字符串。我希望将这个字符串从我的url.py传递到views.py中的MyPhotoIndex类视图。类视图将检查此筛选器类型字符串,并执行正确的逻辑,以相应地按日期或标题排序

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

photoViewer/url.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'),

   ...
)
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/templates/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 %}
<!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>
{%extends'base.html%}
{%block title%}照片索引{%endblock%}
{%block contents%}
照片索引

采取日期:
{%if最新照片列表%} {最新照片列表中照片的百分比%}
  • {{photo.photo_title} {{photo.date_take}

  • {%endfor%} {%else%} 没有可用的照片

    {%endif%} var sortButton=document.getElementById(“sortBtn”); sortButton.onclick=函数(){ //是否将筛选器类型作为字符串附加到URL? location.href=“date\u asc”; }; //addEventListener(“单击”,重定向sortButton,false); {%endblock%}
    photoViewer/templates/photoViewer/base.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 %}
    
    <!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>
    
    
    {%block title%}我的精彩网站{%endblock%}
    
    {%block contents%} {%endblock%}
    &抄袭;公司2014


    您可以使用
    self.args
    self.kwargs
    获取URL参数。更改查询集覆盖
    self.get\u queryset
    。将附加变量传递给模板覆盖
    self.get\u context\u data
    。 例如:

    视图.py

    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
    
       url(r'^photos/(?P<filter_type>[^\d+]*)$', views.PhotoIndexView.as_view(), name='photo_index'),
    
    您可以修改
    get\u 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]
    
    另外,我建议更改
    url.py
    ,类似这样的内容

    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]
    
    url.py

    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
    
       url(r'^photos/(?P<filter_type>[^\d+]*)$', views.PhotoIndexView.as_view(), name='photo_index'),
    
    url(r'^photos/(?P[^\d+]*)$),views.PhotoIndexView.as_view(),name='photo_index'),
    
    变成

       url(r'^photos/(?P<filter_type>(data_desc|title_desc|)$', views.PhotoIndexView.as_view(), name='photo_index'),
    
    url(r'^photos/(?P(data|desc|title|desc|)$),views.PhotoIndexView.as|view(),name='photo|index'),