2

I am trying to save a form with an m2m intermediate table. I get this error when I implement a multiplechoicefield form:

Cannot assign "[Option: Option1]": "StateOption.partoption" must be a "Option" instance.

However, if I comment that out the form will save but can only save 1 option at a time. I would like to be able to have a checklist and have the user select multiple options.

I am using this: Django m2m form save " through " table as a reference but must admit I don't understand it too well, especially the for loop part.

My question is: How do I save the form? I understand why I am getting the instance error but I'm not sure how to solve it. Also, the for loop below is probably wrong. Any advice on how to fix the for loop would be appreciated. It seems like that will allow me to save a multiple choice selection.

models.py

class Disease(models.Model):
    disease = models.CharField(max_length=300, verbose_name="disease")

class Option(models.Model):
    relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
    option = models.CharField(max_length=300, verbose_name="treatment Options")

class State(models.Model):
   state = models.CharField(max_length=300, verbose_name='state')
   relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
   relevantoption = models.ManyToManyField(Option, through='StateOption')

class StateOption(models.Model):
   parttstate = models.ForeignKey(State)
   partoption = models.ForeignKey(Option)
   relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')

forms.py

class StateOptionForm(forms.ModelForm):
    partoption = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=True, widget=forms.CheckboxSelectMultiple) 
    #if I comment the line above out, then my selection will save but only 1 at at time. There are multiple options for a 'state' and I'd like to capture it all at once

    class Meta:
       model = StateOption
       exclude = ['parttstate', 'relevantoutcome']

views.py

def diseasestateoption(request, disease_id, state_id):

    state = get_object_or_404(State, pk=state_id)
    disease = get_object_or_404(Disease, pk=disease_id)  

    if request.method == "POST":
        form = StateOptionForm(request.POST, request.FILES)

        if form.is_valid(): 
           profile = form.save(commit=False)
           profile.user = request.user
           profile.save()

           for state in request.POST.getlist('relevantoption'): #don't really understand this part and I'm probably not implementing this right
               option = StateOption.objects.create(partstate=state, partoption=profile)

       return HttpResponseRedirect(reverse('state', kwargs={'disease_id':disease_id}))

else:
    form = StateOptionForm()

template

 <form class="option_form" action="{% url "diseasestateoption" disease.pk state.pk %}" method="post">{% csrf_token %}

    {{ disease }}
    {{ state }}
    {{option}}

I've posted a similar question here before but did not get the answer. I'm new to django and stackoverflow, so any help would be appreciated.

Edit

I am able to implement this with no intermediate tables and using a save_m2m(), however, I will need an intermediate table for the next part of my program...if I can solve this portion first.

4
  • Hi again. I answered your first post, which was pretty much the same error. Not sure why you deleted that post, but no worries, I'll give it another shot. Also, there's technically not a question in your post...not trying to be difficult just sayin's all :)
    – Fiver
    Commented Aug 24, 2013 at 21:32
  • Hi Pathetique! Sorry about the deletion, I didn't want to go down the road of inlines basically because I was getting the same error. My thinking is not only the instance problem but also that since it's calling an FK, I can only select 1 option at a time (thus I think that's what the 'for' loop is for in the code above)
    – nlr25
    Commented Aug 24, 2013 at 21:35
  • Ok, you don't have to use inline forms to use the formset method I mentioned previously, you can use a modelformset_factory. Also, can you include the Option model code as well?
    – Fiver
    Commented Aug 24, 2013 at 21:40
  • Okay, Just added the option model (added the disease model as well). Then also added the template from your comment below Sorry for the delay.
    – nlr25
    Commented Aug 24, 2013 at 23:28

1 Answer 1

1

Your error:

Cannot assign "[Option: Option1]": "StateOption.partoption" must be a "Option" instance.

is telling you that you are trying to save something into the partoption field that is not an Option instance. Specifically, this is occurring within the for loop of your view in this line:

option = StateOption.objects.create(partstate=state, partoption=profile)

The reason is that profile is not an Option. It is a StateOption instance.

The for loop:

for state in request.POST.getlist('relevantoption'):

indicates that you have specified multiple 'relevantoption' fields in your template. Can you post your template code as well?

Update:

There are several things going on here. First, the models. Let's change the field name to options to make it clearer that that's what they really are:

class State(models.Model):
    state = models.CharField(max_length=300, verbose_name='state')
    relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
    # Note: I've renamed this field to 'options' for clarity
    options = models.ManyToManyField(Option, through='StateOption')

Now, you want a form to specify a State instances's options using checkboxes. We'll create a dedicated form based on the State model to do this:

class UpdateStateWithOptionsForm(forms.ModelForm):
    class Meta:
       model = State
       exclude = ['state', 'relevantdisease']

    def __init__(self, *args, **kwargs):

        # call the parent init
        super(UpdateStateWithOptionsForm, self).__init__(*args, **kwargs)

        # change the widget to use checkboxes
        self.fields['options']forms.ModelMultipleChoiceField(
            queryset=Option.objects.all(), 
            required=True, 
            widget=forms.CheckboxSelectMultiple)

Now we can write the view code to find the option IDs the user chose:

# Note: may not need disease_id if it is supposed to be the state's disease?
def diseasestateoption(request, state_id):

    state = get_object_or_404(State, pk=state_id)

    if request.method == "POST":
        form = UpdateStateWithOptionsForm(request.POST, instance=state)

        if form.is_valid(): 
           for option_id in request.POST.getlist('options'):
               state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id)

       return HttpResponseRedirect(reverse('state', kwargs={'disease_id':state.disease_id}))

    else:
        form = UpdateStateWithOptionsForm(instance=state)

    return render_to_response(
        'some_template.html',
        {
            'form': form,
            'state': state,
        },
        context_instance=RequestContext(request)
    )

Okay, so how does that work? It may help to look at the rendered template HTML. The boilerplate template code for a form:

<form action="{% url 'diseasestateoption' state.pk %}" method="post">
    {% csrf_token %}

    {% if form.non_field_errors %}
        {{ form.non_field_errors }}
    {% endif %}

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

    <button type="submit">Save</button>
</form>

Put that in your template and then visit the page and look at the source code. In HTML form you'll notice a set of inputs all with the name options with each input's value corresponding to the primary key of an Option instance (from the queryset we specified in the ModelForm). The for loop in your view is just grabbing that list and using the Option pk to create an associated StateOption with that Option for the State instance.

Note: this is untested code, there may be bugs crawling around in there!

Hope this helps and good luck!

6
  • Hi Pathetique, I added the question above in the original text. I understand the instance error but I don't know how to solve it. I am trying to save the options from the Option table into the StateOption table.
    – nlr25
    Commented Aug 24, 2013 at 21:39
  • Works! Only minor syntax changes to the code you posted above. Your method saves the values to the database but anytime I change the options, it saves another records in the StateOption table rather than update the previous record. Is there a way to implement a feature like that?
    – nlr25
    Commented Aug 27, 2013 at 18:14
  • To add to my previous comment. The feature I'm thinking to build is that any options related to the state are deleted from StateOption then re-created using StateOption.objects.create. HOpe that's possible. If not, you definitely solved a part of my problem! Greatly appreciated.
    – nlr25
    Commented Aug 27, 2013 at 18:17
  • Great, glad to help. Make sure to accept this answer by clicking on the check mark. For the duplicate related records, probably best to start another question for that.
    – Fiver
    Commented Aug 27, 2013 at 18:56
  • Pathetique, just wondering if you have an idea on the duplicate? Or if you think a better method may be to use modelformsets?
    – nlr25
    Commented Aug 27, 2013 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.