将自定义表单值传递给视图 [英] Passing custom form values to views

查看:118
本文介绍了将自定义表单值传递给视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass values from my custom form to my views.py . However, I can't seem to pass a value for each one of my multiselect options. When rendering there is only 1 charfield but multiple choices in the multichoiceselect. Any ideas? Will formsets be helpful here? Not sure how I'd implement it but any suggestions is appreciated. I'm new to django so explanations would also be helpful for me to learn!

models.py

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

template.html

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

更新

我可以渲染等量的字符现场作为选择。但是,由于resultvalue现在包含多个值,因此无法将其值保存在views.py中。任何想法如何处理?

I can render an equal amount of charfields as choices now. But I am having trouble saving my values in the views.py since outcomevalue now contains multiple values. Any ideas on how to handle it?

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)


推荐答案

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

You need to write a loop to generate required amount of fields. Example:

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'}) 

这篇关于将自定义表单值传递给视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆