我有一个 django formtool 有 2 个步骤。在第一步中,我从多选中选择了一些值,我需要将这些值用于下一次详细说明。根据一些教程(http://blog.hayleyanderson.us/2015/07/26/passing-information-between-django-form-wizard-steps/)我采用第一个表单值但对于多选它只需要最后一个值正如您在图片/打印中看到的那样。
这是我的代码。
表格.py
from django import forms
from station.models import Station
from django.forms import formset_factory
from .models import Vdl
from django.contrib.auth.models import User
station_all = Station.objects.all().values('station_name', 'id_station')
options = ()
i = 0
for st in station_all: #station_all:
station = (st['id_station'], st['station_name']),
if i == 0:
options = options + station
else:
options = options + station
i = i+1
class VdlSelectStationsForm(forms.Form):
vdl_name = forms.CharField(label='nome virtual data logger', max_length=20,
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'}))
stations = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=options)
class Meta:
model = Station
fields = ('station_name')
class VdlSelectSensorsForm(forms.Form):
sensor_list_for_station = forms.ModelMultipleChoiceField(queryset=Vdl.objects.all()) #filter(id_user = id_user))
VdlSelectSensorsFormSet = formset_factory(VdlSelectSensorsForm, extra=1)
视图.py
from django.shortcuts import render
from .forms import VdlSelectStationsForm, VdlSelectSensorsForm
from formtools.wizard.views import SessionWizardView, CookieWizardView
from django.forms import formset_factory
from .forms import VdlSelectSensorsFormSet
from django.contrib.auth.models import User
VdlSelectSensorsFormSet = formset_factory(VdlSelectSensorsForm, formset=VdlSelectSensorsFormSet)
class VdlWizard(SessionWizardView):
template_name = "vdl.html"
form_list = [VdlSelectStationsForm, VdlSelectSensorsForm]
def get_curr_user(self, request):
current_user = self.request.user
print('curr: ', current_user.id)
def get_form_initial(self, step):
initial = {}
id_current_user = self.request.user
id_user = id_current_user.id
if step == '1':
first_step_data = self.storage.get_step_data('0')
print('first_step_data: ', first_step_data, first_step_data.get('0-stations', ''))
# first_step_data: <MultiValueDict: {'csrfmiddlewaretoken': ['Htb8kqUBZgLpsKRxFyx6x1e9eTKiHXo0cVhS2sQB4awANoAfV2oK1NUMyR4k1sKY'], 'vdl_wizard-current_step': ['0'], '0-vdl_name': ['vdl1'], '0-stations': ['345', '1223', '123456']}> 123456
vdl_name = first_step_data['0-vdl_name']
id_vdl_station = first_step_data.get('0-stations', '')
return self.initial_dict.get(step, {'vdl_name': vdl_name, 'id_vdl_station': id_vdl_station})
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
context = {
'form_data': form_data,
}
return render(self.request, 'vdl.html', {'form_data': [form.cleaned_data for form in form_list],})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
不可能取所有 0 站的值吗?