简体   繁体   English

Python模板

[英]Python templates

This is my views.py: 这是我的views.py:

from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
def login(request):
    t = get_template('login.html')
    return HttpResponse(t.render) 

In my urls.py I put 在我的urls.py中

(r'^login/', include('project.views.login')),

to show my templates 显示我的模板

I set my templates directory in settings.py 我在settings.py中设置了我的模板目录

But i got an error named 但我得到一个错误,名为

ImportError at /login/
No module named login

What's wrong ? 怎么了 ?

include is used to include other url configs from other apps. include用于包含来自其他应用程序的其他URL配置。 It shouldn't be used if you're trying to add a url pattern for one particular view. 如果您尝试为一个特定视图添加URL模式,则不应使用它。 You should have something like 你应该有类似的东西

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

The other problem is where you return your response. 另一个问题是您返回响应的位置。 render is a method that takes a context (see the docs ) render是一种获取上下文的方法(参见文档

def login(request):
    t = get_template('login.html')
    c = Context({})
    return HttpResponse(t.render(c)) 

In practice, you wouldn't usually load the template, render it, then return a response. 在实践中,通常不会加载模板,渲染模板然后返回响应。 There are two shortcut functions, render and render_to_response , that cut down on repetition. 有两个快捷函数, renderrender_to_response ,它们减少了重复次数。

You've made a few basic mistakes here. 你在这里犯了一些基本错误。 I recommend you work through the Django tutorials (again, if you've already looked at them). 我建议你通过Django教程(再次,如果你已经看过它们)。 Tutorial 3 in particular explains all this stuff. 教程3特别解释了所有这些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM