我正在尝试将值从我的自定义表单传递给我的 views.py 。但是,我似乎无法为每个多选选项传递一个值。渲染时只有 1 个字符域,但 multichoiceselect 中有多个选项。有任何想法吗?表单集在这里有用吗?不知道我将如何实施它,但任何建议表示赞赏。我是 django 的新手,所以解释也有助于我学习!
模型.py
class StateOption(models.Model):
partstate = models.ForeignKey(State)
partoption = models.ForeignKey(Option)
relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')
class StateOptionOutcome(models.Model):
stateoption = models.ForeignKey(StateOption)
relevantoutcome = models.ForeignKey(Outcome)
outcomevalue = models.CharField(max_length=20)
表格.py
class UpdateStateOptionWithOutcomesForm(forms.ModelForm):
class Meta:
model = StateOption
exclude = ['partstate', 'partoption']
def __init__(self, *args, **kwargs):
super(UpdateStateOptionWithOutcomesForm, self).__init__(*args, **kwargs)
self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.all(),required=True, widget=forms.CheckboxSelectMultiple)
self.fields['outcomevalue']=forms.CharField(widget=forms.TextInput(attrs={'size':'30'}) #when rendering there is only 1 charfield. There should be the same amount of charfields as there are multiplechoicefields.
视图.py
stateoption = get_object_or_404(StateOption, pk=stateoption_id)
if request.method == "POST":
form = UpdateStateOptionWithOutcomesForm(request.POST, instance=stateoption)
if form.is_valid():
cd = form.cleaned_data
outcomevalue = cd['outcomevalue']
for outcome_id in request.POST.getlist('relevantoutcome'):
stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)
模板.html
{% for field in form %}
{{ field.label }}:
{{ field }}
{% if field.errors %}
{{ field.errors|striptags }}
{% endif %}
{% endfor %}
更新
我现在可以渲染等量的字符域作为选择。但是我无法在views.py 中保存我的值,因为结果值现在包含多个值。关于如何处理它的任何想法?
if form.is_valid():
cd = form.cleaned_data
outcomevalue = cd['outcomevalue_1'] #only handles a specific outcomevalue
for outcome_id in request.POST.getlist('relevantoutcome'):
stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)