0
我試圖從我的自定義窗體傳遞值給我的views.py。不過,我似乎無法爲我的多選選項中的每一個選項傳遞一個值。渲染時,multichoiceselect中只有1個charfield,但有多個選項。有任何想法嗎?這裏的formset會有幫助嗎?不知道我會如何實施它,但任何建議表示讚賞。我是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 %}
更新
我現在可以渲染等量的charfields作爲選擇。但是我無法在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)
這確實會爲相關結果生成相同數量的結果值字段。但是,當我嘗試保存值時,我的views.py中出現「outcomevalue」錯誤。是因爲我的結果值只能處理1個值,還是因爲for循環? – nlr25
你現在有很多領域'outcomevalue_ *'。你需要以不同的方式處理它們。 – HankMoody
作爲一種替代方法,是否有更簡潔的方式將結果值與自定義表單中的相關結果相關聯? – nlr25