首页 > 解决方案 > 分配前引用的 Django 局部变量“表单”

问题描述

我正在尝试制作一个表单,用户可以在其中输入该位置的状态并返回该位置的天气

在我在代码中添加city = City.objects.all() 之前它工作正常

from django.shortcuts import render 导入请求 from .models import City

def index(request): cities = City.objects.all() #返回数据库中的所有城市

    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=ec2052730c7fdc28b89a0fbfe8560346'

    if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
    form.save() # will validate and save if validate

    form = CityForm()
    weather_data = []

    for city in cities:

            city_weather = requests.get(url.format(city)).json() #request the API data and convert the JSON to Python data types

            weather = {
            'city' : city,
            'temperature' : city_weather['main']['temp'],
            'description' : city_weather['weather'][0]['description'],
            'icon' : city_weather['weather'][0]['icon']
            }

            weather_data.append(weather) #add the data for the current city into our list

    context = {'weather_data' : weather_data, 'form' : form}
    return render(request, 'weathers/index.html', context)

UnboundLocalError at / local variable 'form' 在分配之前引用请求方法:GET 请求 URL:http: //127.0.0.1 :8000/ Django 版本:2.2.1 异常类型:UnboundLocalError 异常值:分配之前引用的局部变量 'form' 异常位置:索引中的 C:\Users\Admin\Desktop\the_weather\weathers\views.py,第 12 行 Python 可执行文件:C: \Users\Admin\AppData\Local\Programs\Python\Python37-32\python.exe Python 版本:3.7.3 Python 路径:['C:\Users\Admin\Desktop\the_weather', 'C:\Users\Admin \AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Admin\AppData \Local\Programs\Python\Python37-32\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Admin\AppData\Roaming\Python\Python37 \网站包','C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] 服务器时间:Fri, 24 May 2019 04:09:08 +0000

标签: django

解决方案


你需要改变:

    if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
    form.save() # will validate and save if validate
    form = CityForm()

       if request.method == 'POST': # only true if form is submitted
            form = CityForm(request.POST) # add actual request data to form for processing
            if form.is_valid():
                 form.save() # will validate and save if validate
                 # having form in same scope when there is a post request
       else:
           form = CityForm()

推荐阅读