gpt4 book ai didi

python - 赋值前引用的局部变量 'routingForm'

转载 作者:行者123 更新时间:2023-12-04 10:20:23 26 4
gpt4 key购买 nike

我正在尝试提交表单,但收到错误“分配前引用的局部变量‘routingForm’”。请帮我解决这个问题。

*****forms.py*****

   from django import forms
class routingForm(forms.Form):
areaDigit = forms.CharField(label='areaDigit', max_length=100)
product = forms.CharField(label='product', max_length=100)

*****views.py*****
from django.shortcuts import render
from .forms import routingForm

# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from .models import Product,Routing_Dest_Area
def get_route_list(request):
#areaDigit= request.POST.get('areaDigit', False)
#data=Routing_Dest_Area.objects.filter(areaDigit_pk=request.POST['areaDigit'])
if request.method == "POST":
#Get the posted form
routingForm = routingForm(request.POST)

if routingForm.is_valid():
areaDigit = routingForm.cleaned_data['areaDigit']
else:
MyLoginForm = routingForm()

return render(request, 'routing/test.html',{'areaDigit':areaDigit})

*****home.html*****
<form method="POST" action="{% url 'get_route_list'%}" id="routingForm" name="routingForm">
{% csrf_token %}
<div class="form-content">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Area String *"
name"areaDigit" id="areaDigit" value="{{areaDigit}}"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="sel1">Select list (select one):</label>
<select class="form-control" id="Product" name="product">
<option> 1</option>
<option> 21</option>
</select>
</div>
</div>
</div>
<button type="submit" class="btnSubmit">Submit</button>

Form data value in the network tab of inspect element

最佳答案

你不能写routingForm = routingForm(request.POST)因为这使得 routingForm一个局部变量,它在被赋值之前被使用。

但是我强烈建议你写 RoutingForm在 PerlCase 中,因此以大写开头:

# app/forms.py

from django import forms

class RoutingForm(forms.Form):
areaDigit = forms.CharField(label='areaDigit', max_length=100)
product = forms.CharField(label='product', max_length=100)

函数本身的变量,一般都是用snake_case写的。那么 View 看起来像:
# app/views.py

from django.shortcuts import render
from .forms import RoutingForm

from django.http import HttpResponse, HttpResponseRedirect
from .models import Product, Routing_Dest_Area


def get_route_list(request):
areaDigit = None
if request.method == 'POST':
#Get the posted form
routing_form = RoutingForm(request.POST)
if routing_form.is_valid():
areaDigit = routing_form.cleaned_data['areaDigit']
else:
return render(request, 'routing/test.html',{'areaDigit':areaDigit})

关于python - 赋值前引用的局部变量 'routingForm',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60892541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com