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