Django:当函数在另一个目录的视图中时,链接到模板中的URL? [英] Django: link to url in template when function is in a view in another directory?

查看:47
本文介绍了Django:当函数在另一个目录的视图中时,链接到模板中的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在这样的模板中显示评论:

I'm trying to display comments in a template like this:

{{ url note.note }} 
{{ url note.note_by }}

我的问题是我的模板位于请求"注释的视图所在的另一个目录中.如何链接到另一个目录中的视图(或更具体地说,链接到另一个目录中views.py中函数内部的note.note)?

My problem is that my template is in another directory from where the view that "requests" the notes are. How do I link to a view in another directory (or more specifically; the note.note inside a function in a views.py in another directory)?

在SAME目录的views.py中,作为模板,我这样链接到模板:

In the views.py in the SAME directory as the template, I am linking to the template like this:

def blah(request):
   return render(request, 'site/blah.html')

在我请求并保存评论(note.note)的views.py中,看起来像这样:

And in the views.py where I request and save the comments (note.note) look like this:

def messages(request):
if request.method == "POST":
    new_note_text = request.POST.get('new_note')
    new_note = Note()
    new_note.note = new_note_text  
    new_note.note_by = request.user 
    new_note.note_datetime = timezone.now()
    new_note.save()

return render(request, 'theme/messages.html', context)

位于SAME目录中的urls.py作为模板:

urls.py in the SAME directory as the template:

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

urlpatterns = patterns('', 
url(r'^test$', views.blah, name='blah'),
)

settings.py:

settings.py:

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app', 
'theme', 
'site',
 )

 MIDDLEWARE_CLASSES = (
'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',
 )

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
       },
    },
 ]

  WSGI_APPLICATION = 'appen.wsgi.application'


 DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

  LANGUAGE_CODE = 'en-us'

  TIME_ZONE = 'Europe'

  USE_I18N = True

  USE_L10N = True

  USE_TZ = True


  STATIC_URL = '/static/'

推荐答案

Django的反向URL解析器只有一项工作.

Django's reverse url resolver has one job. It takes the arguments fed to it(either through the {% url ... %}" template tag or the urlresolves.reverse in your python code.

只要在启动时您的代码处于有效的Django配置(如下)中,目录模板和视图就无关紧要.此特定示例假定您已将应用程序包含在 settings.py 配置中,并且根 urls.py 包含委派给 urls.py <各个应用程序 main notes

As long as your code is in a valid Django configuration(Below) at start up time the directories templates and views are in isn't relevant. This particular example assumes you've included your apps in the settings.py configuration and that your root urls.py includes entries that delegate to the urls.py files in the individual apps main and notes

- templates
     |
     - main.html
     - notes.html
- main
     |
     - views.py
     - models.py
     - urls.py
- notes
     |
     - views.py
     - models.py 
     - urls.py
- urls.py
- settings.py

您需要什么来工作

所以首先让我们看一下 main ,我必须在 views.py

so first lets look at main I have to create a view function in views.py

from django.shortcuts import render

def main(request):
    return render(request, 'main.html', {})

main/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', main, name='main'),
]

所以这是我的主要观点.假设我想包含< ul> 和来自其他应用程序的各种注释的链接.首先,我需要创建一个 note/< note_id> 视图.我正在使用< note_id> 参数解决我的笔记条目.

So this is my main view. Lets assume I want to include a <ul> with links to various notes from my other app. First things first I need to create a note/<note_id> view. I am using the <note_id> parameter to address my note entries.

我创建了一个notes函数,该函数接受 note_id 关键字参数.

in notes/views.py I create a notes function that takes an note_id keyword argument.

def notes(note_id=None):
    #... Get note from database and put in context
    return render(request, 'notes.html', {})

然后为我们创建的视图创建一个 notes/urls.py 条目.

then create a notes/urls.py entry for the view we've created.

from django.conf.urls import url, patterns
urlpatterns = patterns(
    'main.views',
    url(r'^(?P<note_id>[0-9]+)/?$','notes', name='notes'),
)

然后,我们需要使用 urls.py 根文件

We then need to pull this all together using the root urls.py file

from django.conf.urls import include, url

urlpatterns = [
    url(r'^main/', include('main.urls')),
    url(r'^notes/', include('notes.urls')),
]

所以停下来.我们现在有什么?我们有一个称为 main 的视图,该视图将 context 绑定到 main.html 模板,并作为响应返回一些标记.我们还有一个 urls.py 条目,它告诉Web服务器如何到达该视图.对于不同应用程序中名为 notes 的视图,我们具有完全相同的观点.最后,我们有一个根 urls.py ,它将我特定于应用程序的 urls.py 文件拉到顶层.

So lets stop. What do we have right now? We have a view called main that binds context to the main.html template and returns as a response some markup. We also have a urls.py entry that tells the web server how to reach that view. We have the exact same thing for a view called notes in a different app. Finally, we have a root urls.py that pull my app-specific urls.py files into the top-level.

我们想做什么?我们希望在 main.html 中包含一个< ul> ,其中填充了对我们注释的有效url引用.

What do we want to do? We want to include in main.html a <ul> filled with valid url references to our notes.

由于我们已经进行了所有设置,因此这很容易,因此我们使用 {%url ...%} 模板标签以及适当的信息来解析 urls.py 文件.

Since we already have everything setup this is easy we use the {% url ... %} template tag with the appropriate information to resolve entries from our urls.py files.

在我们的 main.html 模板中,我们仅添加如下内容...

In our main.html template we simply add something like this...

<ul>
    <li> <a href="{% url "notes" note_id=1 %}">note 1</a></li>
    <li> <a href="{% url "notes" note_id=2 %}">note 2</a></li>
    <li> <a href="{% url "notes" note_id=3 %}">note 3</a></li>
</ul>

,当调用 main.html 时,上面的标记类似于...

and when main.html is invoked the markup above will look something like...

<ul>
    <li> <a href="/notes/1">note 1</a></li>
    <li> <a href="/notes/2">note 2</a></li>
    <li> <a href="/notes/3">note 3</a></li>
</ul>

这里要记住的重要事情是 url urlresolver.reverse 的实际作用.它们采用视图名称和一些参数,并将它们转换为字符串形式的有效url.这是一种DRY的url管理方法,因为以后如果将 notes 更改为 notes_important 或所有模板都会自动为您修复所有内容.

The important thing to remember here is what url and urlresolver.reverse actually do. They take a view name and some arguments and they convert them into a valid url as a string. Its a DRY approach to url management because later if you change notes to notes_important or something all of the templates will automatically fix everything for you.

这篇关于Django:当函数在另一个目录的视图中时,链接到模板中的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆