Django的url模板标签如何工作?

时间:2015-05-07 12:16:47

标签: django django-templates templatetags

{"% url 'news_id' %"}如何运作? 我确实有一个网址格式url(r'^((?:\w|-)+)/$', 'comments.views.home', name='news_id'),但我仍然得到NoReverseMatch

它说

  

反转' news_id'参数'()'和关键字参数' {}'未找到。尝试了1种模式:['((?:\ w | - )+)/ $']

views.py

from django.shortcuts import render
from comments.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext, loader, Context
from comments.models import News, User, Comment
from django.core.urlresolvers import resolve 

def home(request, url_arg):
    print "in Views.py", "and url_arg = ", url_arg
    c = Comment.objects.all().filter(news__news_id=url_arg)
    n = News.objects.all().get(news_id=url_arg)
    cont = Context({'news': n.text, 'cts': c, 'news_id': n.news_id})
    rc = RequestContext(request, cont)
    t = loader.get_template('home.html')
    print 'n = ', n
    return HttpResponse(t.render(rc))
    return render(request, 'home.html', context_dict, context_instance=RequestContext(request))

def submit(request):
    print "request.path_info = ", request.path_info
    print "in submit method and url = ", resolve(request.path_info).url_name, " & other try = ", request.resolver_match.url_name 
    news_id = request.POST.get('news_id')
    user_id = request.POST.get('user_id')
    comment_text = request.POST.get('comment')
    print "news_id =", news_id, "user_id = ", user_id, "comment_text = ", comment_text
    n = News(news_id=news_id)
    n.save()
    u = User(name='random',user_id=user_id)
    u.save()
    c = Comment(news=n, user=u, text=comment_text)
    c.save()
    return HttpResponse("Thanks!")

urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    # Examples:
    url(r'^(?:\w|-)+/submit/$','comments.views.submit'),
    url(r'^((?:\w|-)+)/$', 'comments.views.home', name='news_id'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
]

home.html

 <p>
    News: {{news}}<br>
    </p>
    <form action="{% url news_id %}" method="post"> {% csrf_token %}
    User Id: <input type="text" name="user_id"> <br>
    Comment:<br>
    <input type="text" name="comment" placeholder="Express your opinion ...">
    <input type="submit" value="Submit"> <br>

    {% for ct in cts %}
    {{ ct.text }}<br>
    {% endfor %}

</form>

1 个答案:

答案 0 :(得分:3)

你在这里误解了一些事情。特别是,您已混淆了网址格式的名称,以及您需要传递给它的参数

例如,如果您想在博客中捕获帖子的ID并将其传递给详细视图,通常会执行以下操作:

url(r'^(?P<post_id>)/$', views.post_detail, name='post_detail')

因此模式的名称为post_detail,其所使用的参数称为post_id。所以你可以这样做:

{% url "post_detail" post_id=my_post.id %}

另外,你的正则表达式很奇怪。您有一个非捕获组作为捕获组的唯一内容。我无法告诉您实际上是在尝试使用该模式,但通常主页根本不会采用任何参数 - 实际上您实际上并没有传递任何参数。只需使用r'^$'