将自定义表单值传递给视图

时间:2013-08-28 17:35:20

标签: python django django-forms

我正在尝试将值从自定义表单传递到views.py。但是,我似乎无法为我的多选项中的每一个传递值。渲染时,multichoiceselect中只有1个字段但有多个选项。有任何想法吗? formsets会在这里有用吗?不知道我是如何实现它,但任何建议表示赞赏。我是django的新手,所以解释也有助于我学习!

models.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)

forms.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.

views.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) 

template.html

 {% for field in form %}
    {{ field.label }}:
    {{ field }}
    {% if field.errors %}
        {{ field.errors|striptags }}
    {% endif %}
{% endfor %} 

更新

我现在可以选择等量的charfield作为选择。但是我在views.py中保存我的值时遇到问题,因为outcomevalue现在包含多个值。关于如何处理它的任何想法?

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)

1 个答案:

答案 0 :(得分:1)

您需要编写一个循环来生成所需数量的字段。例如:

outcome_qs = Outcome.objects.all()
self.fields['relevantoutcome'] = forms.ModelMultipleChoiceField(queryset=outcome_qs, required=True, widget=forms.CheckboxSelectMultiple)
for outcome in outcome_qs:
    # Use Outcome primary key to easily match two fields in your view.
    self.fields['outcomevalue_%s' % outcome.pk] = forms.CharField(widget=forms.TextInput(attrs={'size':'30'}) 
相关问题