我需要从代码获取价值并重定向到' / value /'提交。
现在我得到了:
'ApartmentForm' object has no attribute 'cleaned_data'
我完全错过了一些东西。
forms.py
class ApartmentForm(ModelForm):
class Meta:
model = Apartment
fields = ['title']
views.py
def index(request):
context = {}
context['apartments'] = get_list_or_404(Apartment)
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
context = {'form': form,}
id = form.cleaned_data.get('id', None)
return redirect(id)
else:
context['apartment_form'] = ApartmentForm
return render(request, 'main/main.html', context)
模板
<form action="/{{ apartment.id }}" method="post">
{% csrf_token %}
<p><select size="10">
<option disabled>Chose apartment</option>
{% for apartment in apartments %}
<option value="{{ apartment.id }}">{{ apartment.title }}</option>
{% endfor %}
</select></p>
<input type="submit" value="Chose">
</form>
更新
谢谢丹尼尔!
在模板中调用表单是如此的失败。我已修复此问题,但仍将None
传递给url(http://127.0.0.1:8000/None)。无法弄清楚原因。
view.py
def index(request):
context = {}
context['apartments'] = get_list_or_404(Apartment)
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
if form.is_valid():
id = form.cleaned_data.get('id', None)
return redirect(id)
else:
context['apartment_form'] = ApartmentForm
return render(request, 'main/main.html', context)
forms.py
APARTMENTS = ()
for apartment in Apartment.objects.all():
APARTMENTS += ((apartment.id, apartment.title),)
class ApartmentForm(Form):
apartment = ChoiceField(label='', widget=Select, choices=APARTMENTS)
模板
<form action="." method="post">
{% csrf_token %}
{{ apartment_form }}
<input type="submit" value="Chose">
答案 0 :(得分:0)
form.cleaned_data
来自form.is_valid()
,因此您可以像这样更改views.py
:
def index(request):
[...]
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
if form.is_valid():
[...]
id = form.cleaned_data.get('id', None)
return redirect(id)