【问题标题】:Passing custom form values to views将自定义表单值传递给视图
【发布时间】:2013-08-28 17:35:20
【问题描述】:

我正在尝试将值从我的自定义表单传递到我的 views.py 。但是,我似乎无法为每个多选选项传递一个值。渲染时只有 1 个字符域,但 multichoiceselect 中有多个选项。有任何想法吗?表单集在这里有用吗?不知道我将如何实施它,但任何建议表示赞赏。我是 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) 

模板.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)

【问题讨论】:

    标签: python django django-forms


    【解决方案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'}) 
    

    【讨论】:

    • 这确实为相关结果产生了相同数量的结果值字段。但是,当我尝试保存值时,views.py 中出现“结果值”错误。是因为我的结果值只能处理 1 个值还是因为 for 循环?
    • 你现在有很多字段outcomevalue_*。您需要以不同的方式处理它们。
    • 作为替代方案,是否有一种更简洁的方式将结果值与自定义表单中的相关结果联系起来?
    猜你喜欢
    • 1970-01-01
    • 2015-05-12
    • 2011-04-11
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多