简单的django框架应用及小项目一

一、用django框架获取全国天气

在我们开始做项目的步骤大概分为四个步骤:

准备阶段

   1.首先,我们在桌面建一个新的文件夹,然后在在这个文件夹里新建项目(在终端里代码创建),新建App,操作过程如下图所示:

   2. -建好项目与App后,我们还需要引入js,还要建立一个模板页,最终成功的页面如下:

3.配置阶段

    1.在setting里面,需要修改三处

扫描二维码关注公众号,回复: 3615420 查看本文章

2.在url里面

3.views里面

4.获取信息并做一下简单处理

from django.shortcuts import render

import requests
# Create your views here.
def index(request):

    if request.method == 'POST':
        city = request.POST['city']
        url = 'http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(city)
    else :
        url = 'http://api.map.baidu.com/telematics/v3/weather?location=%E9%83%91%E5%B7%9E&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'
    json_data = requests.get(url).json()

    weather = json_data['results'][0]['weather_data']

    today_weather = weather[0]
    t_weather = weather[1]
    tt_weather = weather[2]
    ttt_weather = weather[3]

    city = json_data['results'][0]['currentCity']

    context = {
        'today':today_weather ,
        'city' : city ,
        'list': [t_weather ,tt_weather,ttt_weather]
    }
    return  render(request ,'index.html' , context)





    
    
    
    
    

 5.最后在templates模板里面的index里面进行配置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{city}}天气信息</title>
    <style>
        html ,body{
            height:100%;
            margin:0;
            color: white;
            text-align: center;
        }
        body{
            background:linear-gradient(#1078c7,#7196b4);
        }
        form {
            text-align: center;
        }
        main img {
            width:80px;
        }
        h1 {
            margin:5px;
        }
        footer{
            display: flex;
            margin-top:100px;
        }
        section{
            flex-grow:1;
            border-right:1px solid greenyellow;
        }
        section:last-child
        {
            border: none;
        }
    </style>
</head>
<body>
    <form action="/select/" method="POST">
        {% csrf_token %}
        <input name="city" type="text" placeholder="请输入城市">
        <button type="submit">查询</button>
    </form>

    <main>
        <h2>实时天气</h2>
        <img src="{{today.dayPictureUrl}}" alt="">
        <h1>{{today.temperature}}</h1>
        <div>
            {{today.weather}} <br>
            {{today.wind}} <br>
            {{today.date}} <br>
        </div>
    </main>

    <footer>
        {% for weather in list %}
            <section>
                <h4>{{weather.date}}</h4>
                <img src="{{weather.dayPictureUrl}}" alt="">
                <div>
                    {{weather.temperature}} <br>
                    {{weather.weather}} <br>
                    {{weather.wind}} <br>
                </div>
            </section>
        {% endfor %}
    </footer>
</body>
</html>

5.最后是展现页面

猜你喜欢

转载自blog.csdn.net/UserAgent123/article/details/82697560
今日推荐