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

How Django's url template tag works?

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

它说

Reverse for 'news_id' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['((?:\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>

你误解了一些事情。特别是,您混淆了 URL 模式的 name 和需要传递给它的 parameters

例如,如果您想在博客中捕获 post 的 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'^$'.