Django渲染函数给出了最多1个参数的错误dict,得到3

时间:2016-12-18 00:07:26

标签: python django

def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)

    return render(
        request,
        'app/index.html',
        context = RequestContext(request,                                 
        {
            'title':'Home Page'            
        })
    )

我在字典对象中收到错误。

dict预计最多1个参数,得到3

1 个答案:

答案 0 :(得分:0)

正如sly_Chandan所说:不要使用

def home(request):
    return render(
        request,
        'app/index.html',
        {
            'title': 'Home Page'
        }
    )

对于较新的Django,即使是小型应用程序也应该遵循现代模式,请参阅https://docs.djangoproject.com/en/1.11/ref/class-based-views/base/#templateview

from django.views.generic.base import TemplateView

def HomePageView(TemplateView):
    template_name = 'app/index.html'

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['title'] = 'Home Page'
        return context

然后在urls.py

urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
]