Home  >  Article  >  Backend Development  >  Introduction to how Django uses the locals() function

Introduction to how Django uses the locals() function

不言
不言forward
2019-04-15 11:03:113848browse

This article brings you an introduction to the method of using the locals() function in Django. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The locals() function will return all local variables at the current location in dictionary type.

Add in views.py

from django.shortcuts import render,HttpResponse,render_to_response
import datetime
from blog import models

def index(req):
    if req.method=="POST":
        username = req.POST.get("username")
        pwd = req.POST.get("password")

        print(username)
        print(pwd)

        if username == "klvchen" and pwd=="123":
            return HttpResponse("登录成功")
    #return render(req, "login.html")
    kl = "you are welcome"
    a = "hello"
    b = "world"
    c = "what"
    return render_to_response("new.html", locals())

Add new.html in templates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> {{ kl }}</h1>
<h2> {{ a }}</h2>
<h3> {{ b }}</h3>
<h4> {{ c }}</h4>
</body>
</html>

Remember to add the path in urls.py

url(r"index", views.index),

Effect:
Introduction to how Django uses the locals() function

The above is the detailed content of Introduction to how Django uses the locals() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete