如何将对象传递并呈现给扩展的子模板?

时间:2016-11-11 12:38:42

标签: python django django-templates django-views

所以我要做的就是为子模板创建一个视图,这样我就可以传入模型对象和参数,并相应地进行渲染。但是这可能吗?因为两个观点不能被召唤一次?并且两个网址(一个用于子网,一个用于父模板)也不能同时被调用。我不明白它是如何工作的,或者我只是没有正确地看待它。有没有人有任何想法?

urls.py

BV = BoxesView.as_view()

urlpatterns = [
    url(r'^(?P<question_id>[0-9]+)/$', poll, name='poll'), #child template
    url(r'^$', BV, name='news'), #parent template
]

view.py

class BoxesView(ListView):
    template_name = 'polls.html'

    def get_queryset(self):
        queryset_list = Post.objects.all().filter(category=1).order_by('-date')
        return queryset_list


def poll(request, question_id):
    question = get_object_or_404(Question, id=1)
    return render(request, 'polls.html', {'question': question})

polls.html

{% extends 'parent.html' %}

{% block polls %}

<p>question goes here</p> #this shows up
{{ question.question_text }} #this doesn't show up


{% endblock %}

parent.html

{% extends 'base.html' %}

{% block content %}

        {% for post in post_list %}

            {% block polls %}

            {% endblock %}

        {% endfor %}

{% endblock %}

models.py

class Post(models.Model):
    title = models.TextField(max_length=70)

class Question(models.Model):
    question_text = models.CharField(max_length=70)

1 个答案:

答案 0 :(得分:0)

<强> urls.py

如果您孩子模板的网址是:

url(r'^(?P<question_id>[0-9]+)/$', poll, name='poll'), #child template

处理与上述url匹配的请求的视图将由poll视图中提到的url视图处理,其中3个参数传递给它 - 概要为:

url(<regex to match url parameters>, <view to handle the request>, <name of the url>)

<强> views.py

def poll(request, question_id):
    question = get_object_or_404(Question, id=1)
    return render(request, 'polls.html', {'question': question})

view' return声明的摘要:

return render(request, <template name to render>, <the context dictionary for passing anything object/python var to the template>)

因为'poll.html'是您的孩子模板,所以这一切都适合您。

关于将对象传递给child.html - 您已经在此Question传递了{'question': question}个对象,