可能我犯了一些初学者的错误。我正在尝试使用forms.ChoiceField()工作。用户应该能够从下拉列表中进行选择,以便连续选择1,2,3或4个收集器。 当我运行代码时,用户可以从下拉列表中选择选项,但是number_collectors_per_row变量未设置为适当的整数值。
我将choices.py定义如下:
COLLECTORS_PER_ROW_CHOICES = (
(1, 'one collector'),
(2, 'two collectors'),
(3, 'three collectors'),
(4, 'four collectors')
)
系统模型定义如下:
from .choices import *
class System(models.Model):
project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE)
system_name = models.CharField(max_length=200)
number_collector_rows = models.IntegerField(default=1)
number_collectors_per_row = models.IntegerField(choices = COLLECTORS_PER_ROW_CHOICES)
表格定义如下:
from .choices import *
class SystemForm(forms.ModelForm):
number_collectors_per_row = forms.ChoiceField(required=True, choices = COLLECTORS_PER_ROW_CHOICES)
class Meta:
model = System
fields = [
'system_name',
'number_collector_rows'
]
SystemUpdateView定义如下:
class SystemUpdateView(LoginRequiredMixin, UpdateView):
template_name = 'system/detail-update.html'
form_class = SystemForm
def get_object(self):
return System.objects.get(id=self.kwargs['pk_system'])
def get_context_data(self, *args, **kwargs):
context = super(SystemUpdateView, self).get_context_data(*args, **kwargs)
context['title'] = 'Update System'
return context
def get_form_kwargs(self):
kwargs = super(SystemUpdateView, self).get_form_kwargs()
return kwargs
希望有人可以帮助我,提前谢谢。
答案 0 :(得分:0)
尝试将number_collectors_per_row
添加到您的表单Meta.fields
。
class SystemForm(forms.ModelForm):
class Meta:
model = System
fields = [
'system_name',
'number_collector_rows',
'number_collectors_per_row',
]
请注意,由于您在表单中使用与模型相同的选项,因此您无需在表单中重新定义字段。