我是Django的新手,我已經學習了一些關於它的基本知識。我的問題是,我從django模型獲取數據,但我無法將其傳遞/顯示到表單中。我想有一個forms.py,帶有1個phone_id選擇器和3個textInputs,以便將數據插入到所需的手機。從views.py到Django表格的數據
我的models.py:
class Phone(models.Model):
user = models.ForeignKey(User)
num_calls = models.CharField(max_length=20, null=True, blank=True)
time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
psap = models.CharField(max_length=30, null=True, blank=True)
我forms.py:
from django import forms
class phoneForm(forms.Form):
NumberOfCalls = forms.CharField(
min_length = 1,
widget=forms.TextInput({'class': 'form-control'})
)
TimeBetweenCalls = forms.CharField(
widget=forms.TextInput({'class': 'form-control'})
)
PSAP = forms.CharField(
min_length = 1,
widget=forms.TextInput({'class': 'form-control'})
)
def __init__(self, *args, **kwargs):
phone_choices = kwargs.pop('phone_choices')
super(Send2tcu, self).__init__(*args, **kwargs)
self.fields['phone'] = forms.MultipleChoiceField(
required = True,
widget = forms.Select({'class': 'form-control'}),
choices = phone_choices
)
我剛纔創建的表單與3個textInputs和MultipleChoiceField,我需要顯示從型動物中的數據phone_id。
我view.py:
def phone_config(request):
phones = Phone.objects.filter(user_id = request.user.id).values_list('id', flat=True)
if request.method == 'POST':
form = phoneForm(request.POST, phone_choices=phones)
if form.is_valid():
cleaned_data = form.cleaned_data
phone_id = cleaned_data.get('phone')
NumberOfCalls = cleaned_data.get('NumberOfCalls')
TimeBetweenCalls = cleaned_data.get('TimeBetweenCalls')
PSAP = cleaned_data.get('PSAP')
Tcu.objects.filter(id=phone_id).update(
num_calls = NumberOfCalls,
time_btwn_calls = TimeBetweenCalls,
psap = PSAP,
)
return redirect(reverse('gracias'))
else:
form = phoneForm(phone_choices=phones)
return render(request, 'configurer/configurer.html', {'form': form})
def gracias_view(request):
return render(request, 'configurer/gracias.html')
在我看來,首先,我獲取當前用戶的所有phone_id。然後我檢查方法是否發佈,然後從表單中獲取數據,並將不同的phone_ids傳遞給表單。然後檢查表單是否有效,然後創建對象Phone。之後,將不同的參數分配給選定的phone_id並保存。
我的代碼有問題。我收到此錯誤:
TypeError at /configurer/
'int' object is not iterable
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
您能否包含堆棧跟蹤? (你也許想在某個時候閱讀'ModelForm') – Sayse
C:\ Python27 \ lib \ site-packages \ django-1.8.5-py2.7.egg \ django \ forms \ widgets.py in render_options, 539行 – picador