使用 {% url ??? django 模板中的 %}

发布于 2024-10-10 12:24:54 字数 2603 浏览 6 评论 0原文

我在 google 上查找了很多有关如何在模板中使用“url”标签的答案,却发现许多回复说“您只需将其插入模板中并将其指向您想要 url 的视图”。嗯,对我来说没有乐趣:(我已经尝试了所有可能的排列,并且将在这里发布作为最后的手段。

所以就在这里。我的 urls.py 看起来像这样:

from django.conf.urls.defaults import *
from login.views import *
from mainapp.views import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^weclaim/', include('weclaim.foo.urls')),
    (r'^login/', login_view),
    (r'^logout/', logout_view),
    ('^$', main_view),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    #(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/home/arthur/Software/django/weclaim/templates/static'}),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
)

我的“登录”目录中的“views.py”看起来就像:

from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import auth

def login_view(request):
    if request.method == 'POST':
        uname = request.POST.get('username', '')
        psword = request.POST.get('password', '')
        user = auth.authenticate(username=uname, password=psword)
        # if the user logs in and is active
        if user is not None and user.is_active:
            auth.login(request, user)
            return render_to_response('main/main.html', {}, context_instance=RequestContext(request))
            #return redirect(main_view)
        else:
            return render_to_response('loginpage.html', {'box_width': '402', 'login_failed': '1',}, context_instance=RequestContext(request))
    else:
        return render_to_response('loginpage.html', {'box_width': '400',}, context_instance=RequestContext(request))

def logout_view(request):
    auth.logout(request)
    return render_to_response('loginpage.html', {'box_width': '402', 'logged_out': '1',}, context_instance=RequestContext(request))

最后,login_view 指向的 main.html 看起来像:

<html>
<body>
test! <a href="{% url logout_view %}">logout</a>
</body>
</html>

那么为什么我每次都会得到“NoReverseMatch”

(稍微不同的是,我必须在我所有的渲染到响应的结束,因为否则它不会识别我的模板中的 {{ MEDIA_URL }} 并且我无法引用任何 css 或 js 文件,我不确定为什么这看起来不正确。对我来说)

I have looked a lot on google for answers of how to use the 'url' tag in templates only to find many responses saying 'You just insert it into your template and point it at the view you want the url for'. Well no joy for me :( I have tried every permutation possible and have resorted to posting here as a last resort.

So here it is. My urls.py looks like this:

from django.conf.urls.defaults import *
from login.views import *
from mainapp.views import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^weclaim/', include('weclaim.foo.urls')),
    (r'^login/', login_view),
    (r'^logout/', logout_view),
    ('^

My 'views.py' in my 'login' directory looks like:

from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import auth

def login_view(request):
    if request.method == 'POST':
        uname = request.POST.get('username', '')
        psword = request.POST.get('password', '')
        user = auth.authenticate(username=uname, password=psword)
        # if the user logs in and is active
        if user is not None and user.is_active:
            auth.login(request, user)
            return render_to_response('main/main.html', {}, context_instance=RequestContext(request))
            #return redirect(main_view)
        else:
            return render_to_response('loginpage.html', {'box_width': '402', 'login_failed': '1',}, context_instance=RequestContext(request))
    else:
        return render_to_response('loginpage.html', {'box_width': '400',}, context_instance=RequestContext(request))

def logout_view(request):
    auth.logout(request)
    return render_to_response('loginpage.html', {'box_width': '402', 'logged_out': '1',}, context_instance=RequestContext(request))

and finally the main.html to which the login_view points looks like:

<html>
<body>
test! <a href="{% url logout_view %}">logout</a>
</body>
</html>

So why do I get 'NoReverseMatch' every time?

(on a slightly different note I had to use 'context_instance=RequestContext(request)' at the end of all my render-to-response's because otherwise it would not recognise {{ MEDIA_URL }} in my templates and I couldn't reference any css or js files. I'm not to sure why this is. Doesn't seem right to me)

, main_view), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), #(r'^static/(?P<path>.*)

My 'views.py' in my 'login' directory looks like:


and finally the main.html to which the login_view points looks like:


So why do I get 'NoReverseMatch' every time?

(on a slightly different note I had to use 'context_instance=RequestContext(request)' at the end of all my render-to-response's because otherwise it would not recognise {{ MEDIA_URL }} in my templates and I couldn't reference any css or js files. I'm not to sure why this is. Doesn't seem right to me)

, 'django.views.static.serve',{'document_root': '/home/arthur/Software/django/weclaim/templates/static'}), (r'^static/(?P<path>.*)

My 'views.py' in my 'login' directory looks like:


and finally the main.html to which the login_view points looks like:


So why do I get 'NoReverseMatch' every time?

(on a slightly different note I had to use 'context_instance=RequestContext(request)' at the end of all my render-to-response's because otherwise it would not recognise {{ MEDIA_URL }} in my templates and I couldn't reference any css or js files. I'm not to sure why this is. Doesn't seem right to me)

, 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), )

My 'views.py' in my 'login' directory looks like:

and finally the main.html to which the login_view points looks like:

So why do I get 'NoReverseMatch' every time?

(on a slightly different note I had to use 'context_instance=RequestContext(request)' at the end of all my render-to-response's because otherwise it would not recognise {{ MEDIA_URL }} in my templates and I couldn't reference any css or js files. I'm not to sure why this is. Doesn't seem right to me)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

初吻给了烟 2024-10-17 12:24:55

所选答案已过时,没有其他答案为我工作(Django 1.6 并且[显然]没有注册名称空间。)

对于 Django 1.5 及更高版本(来自 文档

警告
不要忘记在函数路径或模式名称两边加上引号!

使用命名 URL,您可以执行以下操作:

(r'^login/', login_view, name='login'),
...
<a href="{% url 'login' %}">logout</a>

如果视图采用另一个参数,则同样简单

def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>

The selected answer is out of date and no others worked for me (Django 1.6 and [apparantly] no registered namespace.)

For Django 1.5 and later (from the docs)

Warning
Don’t forget to put quotes around the function path or pattern name!

With a named URL you could do:

(r'^login/', login_view, name='login'),
...
<a href="{% url 'login' %}">logout</a>

Just as easy if the view takes another parameter

def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>
太阳男子 2024-10-17 12:24:55

您应该在 urls.py 文件中提供一个字符串,而不是导入 logout_view 函数:

所以不是 (r'^login/', login_view),< /code>

(r'^login/', 'login.views.login_view'),

这是标准的处理方式。然后您可以使用以下方法访问模板中的 URL:

{% url login.views.login_view %}

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}
止于盛夏 2024-10-17 12:24:55

确保(django 1.5 及更高版本)将 url 名称放在引号中,如果您的 url 接受参数,则它们应该位于引号之外(我花了几个小时才弄清楚这个错误!)。

{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>

Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).

{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>
北陌 2024-10-17 12:24:55

url 模板标记会将参数作为字符串传递,而不是作为对 reverse() 的函数引用传递。实现此功能的最简单方法是向视图添加一个名称

url(r'^/logout/' , logout_view, name='logout_view')

The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

url(r'^/logout/' , logout_view, name='logout_view')
贪了杯 2024-10-17 12:24:55

从文档来看,我们应该使用命名空间。

在您的情况下,{% url login:login_view %}

From the documentation, we should use namedspace.

In your case, {% url login:login_view %}

空城仅有旧梦在 2024-10-17 12:24:55

例如,my_app1/views.py中有4个视图,如下所示。 *您可以查看文档解释 URL 命名空间详细信息:

# "my_app1/views.py"

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'index.html')

def test1(request):
    return HttpResponse("Test1")

def test2(request):
    return HttpResponse("Test2")

def test3(request):
    return HttpResponse("Test3")

并且,my_app1/urls.py中有2个路径,如下所示:

# "my_app1/urls.py"

from django.urls import path
from . import views

app_name = "my_app1"

urlpatterns = [
    path('test1/', views.test1, name="test1"),
    path('test2/', views.test2, name="test2"),
]

并且,core/urls.py中有4个路径,如下所示:

# "core/urls.py"

from django.contrib import admin
from django.urls import path, include
from my_app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('my_app1/', include('my_app1.urls')),
    path('test3/', views.test3, name='test3'),
]

现在,您可以将这些 URL 命名空间设置为 url 标记 index.html如下所示:

{% "index.html" %}

<a href="{% url 'admin:index' %}">Admin</a>
<a href="{% url 'my_app1:test1' %}">Test1</a>
<a href="{% url 'my_app1:test2' %}">Test2</a>
<a href="{% url 'test3' %}">Test3</a>

For example, there are 4 views in my_app1/views.py as shown below. *You can see the doc explaining URL namespaces in detail:

# "my_app1/views.py"

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'index.html')

def test1(request):
    return HttpResponse("Test1")

def test2(request):
    return HttpResponse("Test2")

def test3(request):
    return HttpResponse("Test3")

And, there are 2 paths in my_app1/urls.py as shown below:

# "my_app1/urls.py"

from django.urls import path
from . import views

app_name = "my_app1"

urlpatterns = [
    path('test1/', views.test1, name="test1"),
    path('test2/', views.test2, name="test2"),
]

And, there are 4 paths in core/urls.py as shown below:

# "core/urls.py"

from django.contrib import admin
from django.urls import path, include
from my_app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('my_app1/', include('my_app1.urls')),
    path('test3/', views.test3, name='test3'),
]

Now, you can set these URL namespaces to url tag in index.html as shown below:

{% "index.html" %}

<a href="{% url 'admin:index' %}">Admin</a>
<a href="{% url 'my_app1:test1' %}">Test1</a>
<a href="{% url 'my_app1:test2' %}">Test2</a>
<a href="{% url 'test3' %}">Test3</a>
夏夜暖风 2024-10-17 12:24:55

从你的例子来看,不应该是 {% url myproject.login.views.login_view %} 故事结束吗? (将 myproject 替换为您的实际项目名称)

Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文