首页 > 其他 > 详细

django-模板中if标签的应用

时间:2021-08-01 22:29:53      阅读:20      评论:0      收藏:0      [点我收藏+]

模板视图option标签+if判断

views

from django.http import  HttpResponse
from django.shortcuts import render

def mycal(request):
    if request.method==‘POST‘:
        x=int(request.POST[‘x‘])
        y=int(request.POST[‘y‘])
        cal=request.POST[‘cal‘]
        if cal==‘add‘:
            result=x+y
        
        elif cal==‘sub‘:
            result=x-y
        elif cal==‘mul‘:
            result=x*y
        elif cal==‘div‘:
            result=x/y
        return  render(request,‘test.html‘,locals())
    elif request.method==‘GET‘:

        return render(request,‘test.html‘)

url配置

from django.urls import path
from  . import views
urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘mycal/‘,views.mycal)
]

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试页面计算</title>
</head>
<body>
    <form action= ‘/mycal/‘ method="POST">
        {% csrf_token %}
    <input type="text" name=‘x‘ value={{x}}>
    <select name="cal" >
        <option value="add" {% if cal == ‘add‘ %} selected{% endif %}> +加</option>
        <option value="sup" {% if cal == ‘sup‘ %} selected{% endif %}>-减</option>
        <option value="mul" {% if cal == ‘mul‘ %} selected{% endif %}>*乘</option>
        <option value="div" {% if cal == ‘div‘ %} selected{% endif %}>/除</option>



    </select>
    
    <input type="text" name="y" value={{y}}>
    =<span>{{result}}</span> 
    </br>
    <input type="submit" value=‘计算结果‘>
    </form>
</body> 
</html>

网页内容显示
技术分享图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试页面计算</title>
</head>
<body>
    <form action= ‘/mycal/‘ method="POST">
        <input type="hidden" name="csrfmiddlewaretoken" value="24xDImyFe8BGhoPqSU1V5bhRtf9O5ERvq2y7QfdxnmEZH62tr0BuZss6PP4yjLPm">
    <input type="text" name=‘x‘ value=15>
    <select name="cal" >
        <option value="add" > +加</option>
        <option value="sup" >-减</option>
        <option value="mul" >*乘</option>
        <option value="div"  selected>/除</option>



    </select>
    
    <input type="text" name="y" value=20>
    =<span>0.75</span> 
    </br>
    <input type="submit" value=‘计算结果‘>
    </form>
</body> 
</html>

django-模板中if标签的应用

原文:https://www.cnblogs.com/yescarf/p/15087796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!