要在网站主页上创建表单,我创建了一个表单类和一个请求类。 不知怎的,我无法将响应收到url querystring。
有人可以帮我这个吗?
views.py
def index(request):
if request.method == 'GET':
form = CurrencyConverterForm(request.GET)
if form.is_valid():
base_currency = form.data.__getitem__('base_currency')
counter_currency = form.data.__getitem__('counter_currency')
base_amount = form.data.__getitem__('base_amount')
counter_amount = get_conversion_amount(base_currency, counter_currency, datetime.now(), base_amount)
response = HttpResponseRedirect('/')
response['base_currency'] = base_currency
response['counter_currency'] = counter_currency
response['base_amount'] = base_amount
return response
else:
form = CurrencyConverterForm()
context = {'form': form}
return render(request, '../templates/client/index.html', context)
forms.py
class CurrencyConverterForm(forms.Form):
base_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=True)
counter_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=True)
base_amount = forms.FloatField(required=True)
urls.py
urlpatterns = [
url(r'^$', views.index),
url(r'^admin/', admin.site.urls),
]
的index.html
<form action="" method="get">
{{ form.as_ul }}
<input type="submit" value="Convert"/>
</form>
答案 0 :(得分:1)
您需要像这样访问表单数据:
data = form.cleaned_data['data']
所以你的观点必须如下:
def index(request):
if request.method == 'GET':
form = CurrencyConverterForm(request.GET)
if form.is_valid():
base_currency = form.cleaned_data['base_currency']
counter_currency = form.cleaned_data['counter_currency']
base_amount = form.cleaned_data['base_amount']
counter_amount = get_conversion_amount(base_currency, counter_currency, datetime.now(), base_amount)
response = HttpResponseRedirect('/')
response['base_currency'] = base_currency
response['counter_currency'] = counter_currency
response['base_amount'] = base_amount
return response
else:
form = CurrencyConverterForm()
context = {'form': form}
return render(request, '../templates/client/index.html', context)
答案 1 :(得分:0)
我已经能够解决它。
我实际上需要的代码少得多。
fillViewport="true"