Django:如何通过单击一行来更改页面?

Django: How to change the page at the click of a line?

当我单击 HTMl 中标记中的一行时,我试图在 Ddjango 中创建一些视图,我需要一些建议,请考虑到我是 Django 的初学者。 事实上,我想在单击它时更改我的视图,这将在我的标签内打开一个名为 Hash 的新视图。 让我用这个名为 bap2pmonitoring.html:

的代码向你解释
{% load staticfiles %}
<!DOCTYPE html>
<html lang="fr">
<head>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />
</head>
<body>

<h1> BAP2P Monitoring</h1>


<table>
    <tr>
        <th width=550 height=20>Torrent Hash</th>
        <th width=720 height=20>Torrent Name</th>
        <th width=120 height=20>Size</th>
        <th width=170 height=20>Active Peers</th>
    </tr>

{% for torrent in torrents %}
        <p id="demo">
        <tr bgcolor=eeeeee> 
            <td width=550 height=20><a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a></td>
            <td width=720 height=20>{{ torrent.Name }}</td>
            <td width=120 height=20>{{ torrent.Size }}</td>
            <td width=170 height=20></td>
    </tr>
        </p>
{% endfor %}

</table>

</body>
</html>

我因此得到这个结果:

![在此处输入图片描述][1]

我的想法是,当我单击这两行之一时,它会呈现一个新视图,其中包含有关此 torrent 的信息以及 torrent 的哈希值 url,如下所示:

127.0.0.1:8000/torrents/606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b

按照 Django 教程,我尝试了很多事情都没有成功,然后我尝试 "onclick" 在我的 view.py 中启动我的一个 def,如下所示:

from django.shortcuts import render_to_response
from django.template import Template , Context
from polls.models import Torrent
# Create your views here.
# -*- coding: utf-8 -*-

def home(request):  
    return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})


def details(request, torrent_hash):
    return render_to_response('mysite/detail_torrent.html', {'torrents':Torrent.objects.filter(hash=torrent_hash)})

我还尝试将散列显示为 url,就像在 urls.py 中这样:

from django.conf.urls import patterns,include, url
from django.contrib import admin
from polls.models import Torrent

urlpatterns = patterns('polls.views',

     url(r'^torrents$', 'home', name = 'home'),
     url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'),
     url(r'^admin/', include(admin.site.urls)),
)

我不明白我该如何解决这个问题,欢迎和赞赏任何想法

现在我得到这个错误页面:

NoReverseMatch at /torrents

Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

以及这个回溯:

   Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/torrents

Django Version: 1.8.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Template error:
In template /home/florian/Documents/mysite/templates/mysite/bap2pmonitoring.html, error at line 23
   Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

   13 :     <tr>



   14 :         <th width=550 height=20>Torrent Hash</th>



   15 :         <th width=720 height=20>Torrent Name</th>



   16 :         <th width=120 height=20>Size</th>



   17 :         <th width=170 height=20>Active Peers</th>



   18 :     </tr>



   19 : 



   20 : {% for torrent in torrents %}



   21 :         <p id="demo">



   22 :         <tr bgcolor=eeeeee> 



   23 :             <td width=550 height=20><a href=" {% url 'hash' torrent.Hash %} ">{{ torrent.Hash }}</a></td>



   24 :             <td width=720 height=20>{{ torrent.Name }}</td>



   25 :             <td width=120 height=20>{{ torrent.Size }}</td>



   26 :             <td width=170 height=20></td>



   27 :         </tr>



   28 :         </p>



   29 : {% endfor %}



   30 : 



   31 : </table>



   32 : 



   33 : </body>


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/florian/Documents/mysite/polls/views.py" in home
  8.     return render_to_response('mysite/bap2pmonitoring.html', {'torrents':Torrent.objects.all()})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render_to_response
  39.         content = loader.render_to_string(template_name, context, using=using)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  99.         return template.render(context, request)
File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py" in render
  74.         return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  209.                     return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
  201.         return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
  903.                 bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
  79.             return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  217.                             nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  507.                         six.reraise(*exc_info)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
  493.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
  579.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  496.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /torrents
Exception Value: Reverse for 'hash' with arguments '(u'606d4759c464c8fd0d4a5d8fc7a223ed70d31d7b',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['torrents/(?P<torrent_hash>)/$']

您需要:

更改您的详细视图的上下文以仅访问一个 torrent,并且还包括您在 URL:

中的论点
details(request, torrent_hash):
    return render_to_response('mysite/detail_torrent.html', {'torrent':Torrent.objects.filter(hash=torrent_hash)})

像这样使用 URL,它通过您的 torrent 哈希传递到视图:

 url(r'^torrents/(?P<torrent_hash>)/$', 'details', name = 'hash'),

您还需要 detail_torrent.html 模板,然后您可以在其中使用 'torrent' 上下文。

编辑以抢占另一个问题:

在您的主模板中,您可以使用此更改 link 到 torrent。然后,您将 torrent.Hash 变量作为参数传递给 URL,它将用于 URL 正则表达式中的 torrent_hash:

{% for torrent in torrents %}
    <p id="demo">
    <tr bgcolor=eeeeee> 
        <td width=560 height=20><a href="{% url 'hash' torrent.Hash %}">{{ torrent.Hash }}</a></td>
        <td width=710 height=20>{{ torrent.Name }}</td>
        <td width=110 height=20>{{ torrent.Size }}</td>
        <td width=110 height=20></td>
    </tr>
    </p>
{% endfor %}

onlick 属性不会调用您的服务器端视图函数。它是一个 JavaScript 偶数处理程序,因此它将寻找一个名为 details() 的 JS 函数,因为它看起来不像你有一个它不会做任何事情。您可以通过打开浏览器开发工具并转到 "Console" 选项卡来确认这一点。一旦你在那里点击你的行,你会看到看起来像这样的东西:

Uncaught ReferenceError: details is not defined

您将需要编写一个 JS 函数来返回您的服务器,以便您的服务器可以发送一个新页面进行呈现。我强烈建议为此使用 jQuery,因为它会让您的生活变得更加简单。

首先你需要修改你的 HTML 因为有几处错误:

{% for torrent in torrents %}
    <tr class="torrent" id="{{ torrent.Hash }}" > 
      <td width=550 height=20>{{ torrent.Hash }}</td>
      <td width=720 height=20>{{ torrent.Name }}</td>
      <td width=120 height=20>{{ torrent.Size }}</td>
      <td width=170 height=20></td>
    </tr>
{% endfor %}

id HTML 元素的属性应该是唯一的,稍后我们将在我们的 JS 中使用它来获得正确的 URL。没有必要将 <tr> 包装在 <p> 标签中,所以让我们去掉它。我添加了一个 class 让我们在编写 JS 时更轻松一些。

现在的 JS:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
  $(".torrent").on('click', function(){
    var hash = $(this).attr('id');
    window.location.href = '/torrents/' + hash;
  });
</script>

请务必将此添加到模板中结束 <body> 标记的正上方。

或者,您不能添加 CSS class 并使用此 jQuery 选择器 $('tr'),但仅当这是唯一的 table 时才这样做在页面上。

这将为您创建一个 URL,然后在您单击 table 行的任意位置时打开该 URL。

urlpatterns = patterns('polls.views',
     url(r'^torrents$', 'home', name = 'home'),
     url(r'^torrents/(?P<torrent_hash>)/$', 'details', name='hash'),  # this line
     url(r'^admin/', include(admin.site.urls)),
)

您将需要调整我指示的线路,以便其正常工作。最后修改您的视图以接受您的新参数:

def details(request, torrent_hash):
    return render_to_response('mysite/detail_torrent.html', {'torrents':Torrent.objects.get(Hash=torrent_hash)})

编辑:再一步,让用户明白他们可以单击 table 行转到新的 url,您会希望在 CSS :

.torrent:hover {
  cursor: pointer;
}

多亏了拉尔夫的建议,我才成功地完成了与发帖者相同的事情。但是,通过一个调整,即我(有意)停留在初始页面上,即在上面的示例中我只使用

'mysite/bap2pmonitoring.html'

我在哪里调用

<a href="{{ url 'hash' torrent.Hash }}">{{ torrent.Hash }}</a> 

(在 for 循环内)

视图因此指向 'mysite/bap2pmonitoring.html' 而不是 'mysite/detail_torrent.html'

就 link 而言一切正常。但是,一旦我单击 link,并(正确)显示详细信息视图的结果,循环的 link 就会消失。初始页面的其他所有内容都保留了下来。有没有办法防止这种情况,即保留 links?

(想法是创建一个面板并在下面显示详细信息,可以通过面板的 link 更新详细信息)