django - 分配前引用的 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
解决方案
你需要改变:
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()
推荐阅读
- excel - 为什么我的复制粘贴粘贴代码本身?
- moqui - 处理 Moqui 列表中地图必填字段的验证
- gcc - 汇编:没有这样的指令`iretd`?我可以用什么代替?i686-elf-gcc
- c++ - 在 Linux 中使用 -fvisibility=hidden 编译时出现库加载错误
- mysql - 在 mysql > CLI 中搜索和替换所有出现的单词
- c# - 数据网格视图中的外键数据绑定 - 具有多行的组合框
- python - 如何将 scipy.optimize.fmin 与向量而不是标量一起使用
- javascript - 在字符串javascript的左侧和右侧找到第一次出现的字符
- python - 使用 any() 从字符串列表中识别匹配的字符串?
- c++ - 通过dll从64位程序访问32位程序