将模板中的值(单词符号和数字)传递到django中的url.py

时间:2015-04-28 02:43:08

标签: regex django

我是django的新人。我想从模板传递日志文件名,以查看日志文件名是Fuze-2015-04-28-08-07-34_28744226_30892878.log。当我点击html中的标签时,它会给我一个错误page not found

错误 NoReverseMatch在/ 使用参数'('Fuze-2015-04-27-00-42-55.log',)'和关键字参数'{}'找不到'parselog'的反转。尝试了1种模式:['parselog /(?P [ - \ w] +)/ $']

模板渲染期间出错

在模板C:\ fuzeLog \ fuzeLog \ templates \ index.html中,第61行出错 使用参数'('Fuze-2015-04-27-00-42-55.log',)'和关键字参数'{}'找不到'parselog'的反转。尝试了1种模式:['parselog /(?P [ - \ w] +)/ $']

61:{{logfile}}

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="row">
<div class="col-xs-6 col-sm-4" style='overflow:auto; width:400px; height:500px;'>
{% for logfile in logfiles %}
<a href="{% url 'parselog' logfile %}">{{ logfile }}</a>
<br>
{% endfor %}
</div>
</div>
</body>
</html>

urls.py

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

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:

    url(r'^$', 'fuzeLogApp.views.home', name='home'),
    url(r'^parselog/(?P<logfile>[-\w]+)/$', 'fuzeLogApp.views.parselog', name='parselog'),


    url(r'^admin/', include(admin.site.urls)),
)

view.py

def home(request):
    try:
        OSName = platform.system()
        print OSName

        if OSName == "Windows":
            path="C:\\Users\\Ish_waR\\AppData\\Local\\FuzeBox\\Logs"  # insert the path to your directory
            Logfile_list =os.listdir(path) 
        else:
            pass

    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
        return render_to_response('index.html',{'OSName':"I/O error({0}): {1}".format(e.errno, e.strerror)},context_instance=RequestContext(request))

    return render_to_response('index.html',{'OSName':OSName ,'logfiles': Logfile_list},context_instance=RequestContext(request))

def parselog(request,logfile):
   print logfile

1 个答案:

答案 0 :(得分:1)

在index.html中使用url template tag,并将logfile变量作为参数传递

{% for logfile in logfiles %}
<a href="{% url 'parselog' logfile %}">{{ logfile }}</a>
<br>
{% endfor %}

在urls.py中,您需要允许'。'在正则表达式中:

url(r'^parselog/(?P<logfile>[\w.-]+)/$', 'fuzeLogApp.views.parselog', name='parselog'),

请参阅Common Regular Expressions for Django URLs