Note that there are some explanatory texts on larger screens.

plurals
  1. POefficient way to save custom form fields to database
    primarykey
    data
    text
    <p>I am have trouble saving many fields into a database. I have a many 'outcomevalue_#' fields that get generated based on the number of outcomes I have. The user selects a subset of outcomes(relevantoutcomes) and enters the associated values. I'd like to save the associated values with the outcomes. So far I can only hardwire the field names which does not solve the problem.</p> <p>views.py</p> <pre><code>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_1'] #hardwired. This needs to be generalized. for outcome_id in request.POST.getlist('relevantoutcome'): stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue) </code></pre> <p>forms.py</p> <pre><code>class UpdateStateOptionWithOutcomesForm(forms.ModelForm): class Meta: model = StateOption 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) outcome_qs=Outcome.objects.all() for outcome in outcome_qs: self.fields['outcomevalue_%s' % outcome.pk] = forms.CharField(required=False) </code></pre> <p><strong>Update</strong></p> <p>Here is my stripped down models.py</p> <pre><code>class StateOptionOutcome(models.Model): stateoption = models.ForeignKey(StateOption) relevantoutcome = models.ForeignKey(Outcome) outcomevalue = models.CharField(max_length=20) </code></pre> <p>After some playing around I have something like: </p> <pre><code> outcomelist = request.POST.getlist('relevantoutcome') for outcome_id in outcomelist: cd = form.cleaned_data outcomevalue = cd['outcomevalue_%s' % outcomelist[int(outcome_id)]] stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue) </code></pre> <p>but get error:</p> <pre><code>list index out of range </code></pre> <p>because it is grabbing the values in the list rather than the index position</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload