在我的Django应用程序中,我有一个带有ModelChoiceField
的索引视图,用于选择对象。当我单击提交按钮时,我想将该对象传递给下一个视图,但它不起作用。
这是我的代码: 的观点:
def index(request):
args = {}
args.update(csrf(request))
if request.user.is_authenticated():
if request.POST:
form = EquipmentForm(request.POST)
if form.is_valid():
form.save()
request.session['chosen_equipment'] = form.cleaner(self)
return HttpResponseRedirect('/lru/reservation/')
else:
form = EquipmentForm()
args['form'] = form
args['user'] = request.user
args['reservation_list'] = Reservation.objects.all()
return render_to_response('lru/index.html', args)
else:
return HttpResponseRedirect('/lru/login/')
def reservation(request):
if request.POST:
form = ReservationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/lru/')
else:
form = ReservationForm()
form = ReservationForm(initial={'reserved_by': request.user})
args = {}
args.update(csrf(request))
args['form'] = form
args['chosen_equipment'] = request.session.get('chosen_equipment', ' Not found')
return render_to_response('lru/reservation.html', args)
形式:
class EquipmentForm(forms.Form):
class Meta:
model = Equipment
equipment = forms.ModelChoiceField(queryset=Equipment.objects.all())
def cleaner(self):
data = self.cleaned_data[equipment]
return data
我在这里做错了什么?
答案 0 :(得分:0)
试试这个版本,它应该符合您的期望:
您的forms.py
:
class EquipmentForm(forms.Form):
class Meta:
model = Equipment
equipment = forms.ModelChoiceField(queryset=Equipment.objects.all())
在views.py
中,这应该有效:
from django.shortcuts import redirect
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def index(request):
args = {}
args['user'] = request.user
args['reservation_list'] = Reservation.objects.all()
if request.user.is_authenticated():
if request.POST:
form = EquipmentForm(request.POST)
if form.is_valid():
form.save()
request.session['chosen_equipment'] = form.cleaned_data['equipment']
return redirect('/lru/reservation/')
else:
# Form invalid, so render the same view again
args['form'] = form
return render(request, 'lru/index.html', args)
else:
form = EquipmentForm()
args['form'] = form
return render(request, 'lru/index.html', args)
else:
return redirect('/lru/login/')
@login_required
def reservation(request):
args = {}
args['chosen_equipment'] = request.session.get('chosen_equipment', ' Not found')
if request.POST:
form = ReservationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/lru/')
else:
# Always have an else condition if the form doesn't validate
args['form'] = form
return render(request, 'lru/reservation.html', args)
else:
form = ReservationForm(initial={'reserved_by': request.user})
args['form'] = form
return render(request, 'lru/reservation.html', args)
的变化:
cleaned_data
。redirect
快捷方式,这种方式更加灵活。render
快捷方式,以便正确传递RequestContext
。login_required
装饰器,以确保只有登录用户才能调用视图。