2018-07-13 10:57:24 332浏览
今天扣丁学堂给大家主要介绍关于Python培训之Django框架中方法的访问和查找,包括各种列表和字典的查找,是Python的Django框架使用的必备技巧,在Django模板中遍历复杂数据结构的关键是句点字符(.)。比如假设你要向模板传递一个Python字典。要通过字典键访问该字典的值,可使用一个句点,下面我们一起来看一下吧。
>>>fromdjango.templateimportTemplate,Context >>>person={'name':'Sally','age':'43'} >>>t=Template('{{person.name}}is{{person.age}}yearsold.') >>>c=Context({'person':person}) >>>t.render(c) u'Sallyis43yearsold.'
>>>fromdjango.templateimportTemplate,Context >>>importdatetime >>>d=datetime.date(1993,5,2) >>>d.year 1993 >>>d.month 5 >>>d.day 2 >>>t=Template('Themonthis{{date.month}}andtheyearis{{date.year}}.') >>>c=Context({'date':d}) >>>t.render(c) u'Themonthis5andtheyearis1993.'
>>>fromdjango.templateimportTemplate,Context >>>classPerson(object): ...def__init__(self,first_name,last_name): ...self.first_name,self.last_name=first_name,last_name >>>t=Template('Hello,{{person.first_name}}{{person.last_name}}.') >>>c=Context({'person':Person('John','Smith')}) >>>t.render(c) u'Hello,JohnSmith.'
>>>fromdjango.templateimportTemplate,Context >>>t=Template('{{var}}--{{var.upper}}--{{var.isdigit}}') >>>t.render(Context({'var':'hello'})) u'hello--HELLO--False' >>>t.render(Context({'var':'123'})) u'123--123--True'
>>>fromdjango.templateimportTemplate,Context >>>t=Template('Item2is{{items.2}}.') >>>c=Context({'items':['apples','bananas','carrots']}) >>>t.render(c) u'Item2iscarrots.'
>>>fromdjango.templateimportTemplate,Context >>>person={'name':'Sally','age':'43'} >>>t=Template('{{person.name.upper}}is{{person.age}}yearsold.') >>>c=Context({'person':person}) >>>t.render(c) u'SALLYis43yearsold.'
以上就是关于扣丁学堂Python视频教程Django框架中方法访问和查找详解介绍,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。扣丁学堂有专业的Python视频教程供大家在线学习,不仅有时俱进的课程体系还有专业的老师授课,定能让你轻松学习,高薪就业。扣丁学堂Python技术交流群:279521237。
【关注微信公众号获取更多学习资料】