2013-08-28 2 views
0

사용자 정의 양식에서 내 views.py로 값을 전달하려고합니다. 그러나 다중 선택 옵션 하나 하나에 가치를 전달할 수 없습니다. 렌더링 할 때 charfield는 1 개 뿐이며 multichoiceselect에는 여러 개의 선택 사항이 있습니다. 어떤 아이디어? 활자체가 여기에 도움이 될 것입니까? 어떻게 구현할지 모르겠지만 어떤 제안이라도 감사드립니다. 나는 장고에 대한 새로운 지식을 가지고 있으므로 배울 때 도움이 될 것입니다.보기에 사용자 정의 양식 값 전달

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를 렌더링 할 수 있습니다. 그러나 outcomevalue에는 이제 여러 값이 포함되어 있으므로 views.py에 내 값을 저장하는 데 문제가 있습니다. 그것을 처리하는 방법에 대한 아이디어?

답변

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

관련 outcome에 대해 동일한 수의 outcomevalue 필드가 생성됩니다. 그러나 값을 저장하려고하면 내 views.py에서 "outcomevalue"오류가 발생합니다. 내 결과 값은 1 개의 값만 처리 할 수 ​​있기 때문에 아니면 for 루프 때문입니까? – nlr25

+0

이제 'outcomevalue_ *'필드가 여러 개 있습니다. 볼 때 다르게 처리해야합니다. – HankMoody

+0

대안으로, outcomevalue와 customout 양식의 relevantoutcome을 연결하는 더 깨끗한 방법이 있습니까? – nlr25