将模板中的值传递给Django中的视图

时间:2013-07-28 17:04:45

标签: django python-2.7 django-templates views django-urls

也许这很容易,但我遇到了麻烦。

我需要将template.html中的值传递给view.py我已经在google和django docs中搜索了这个问题但是建立的唯一解决方案是使用:URL(GET)是否有另一种形式?

我在course_main.html中有这个:

{% for Course in Course %}
                <div id='courseContainer'>
                            <h4 class="center"> {{ Course.name }} </h4>
                            <a href="course/{{ Course.name }}"><img class="center" src="{{ Course.image.url }}"/></a>
                            <p class="center"> {{ Course.date }} </p>
                            <p> {{ Course.description }} </p>
                <!--End courseContainer -->
                </div>
{% endfor %}

因此,当用户按下时:&lt;'img class =“center”src =“{{Course.image.url}}”/&gt;  这会重定向到{{Course.name}}

中的变量

这是由urls.py中的explicit_course处理:

urlpatterns = patterns('',
#Courses
(r'^course/[a-z].*$',explicit_course),

这是explicit_course views.py:

def explicit_course(request):
profesor = Professor.objects.get(id=1)
courseExplicit = Course.objects.get(name="django-python")
variables = RequestContext(request,{
    'CourseExplicit':courseExplicit,
    'Profesor':profesor
})
return  render_to_response('course_explicit.html',variables)

我想做这样的事情:

courseExplicit = Course.objects.get(name="Course.name")

但我不知道如何将course_main.html中的课程值传递给views.py中的explicit_course

任何人都可以帮助我吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

您需要更改urls.py以使用命名的正则表达式:

urlpatterns = patterns('',
#Courses
(r'^course/(?P<course_name>[a-z]+)$',explicit_course),
)

然后更改您的explicit_course视图说明:

def explicit_course(request, course_name):
    profesor = Professor.objects.get(id=1)
    courseExplicit = Course.objects.get(name=course_name)
    # etc...

urls.py中的命名正则表达式匹配会将其内容作为变量传递给视图(request之后),然后您可以正常使用。

你并不是真的'从模板传递价值到视图',你只是从网址中提取数据。

可在此处找到文档,值得一读:https://docs.djangoproject.com/en/1.5/topics/http/urls/#named-groups