Home > Enterprise >  Creating a multiplechoice field using many to many relationship
Creating a multiplechoice field using many to many relationship

Time:10-25

Im trying to add a field called, interested_fields inside my personalInfo model which users can choose from and the choices themselves come from another models' objects with the help of ManyToMany relation between the two models. Here are my models.py codes(I simplified my personal model by removing some other fields like name, age, etc in order to make it more readable for you):

class Field(models.Model):
    id = models.AutoField(primary_key=True)
    slug = models.CharField(max_length=16, default='default')
    title = CharField(max_length=32)


class PersonalInfo(models.Model):
    id = models.AutoField(primary_key=True)
    interested_fields = models.ManyToManyField(Field, blank=True)

then, I created a ModelForm like this:

class InterestedFieldsForm(forms.ModelForm):
    interested_fields = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=Field.objects.all(), required=False)

    class Meta:
        model = PersonalInfo
        fields = ['interested_fields']

and created a get and post functions inside my views like this:

class PersonalView(View):
    template_name = 'reg/personal.html'

    def get(self, request, *args, **kwargs):
        context = {}
        context['fields'] = Field.objects.all()
        return render(request, self.template_name, context=context)

    def post(self, request, *args, **kwargs):
        user = request.user
        if request.method == 'POST':
            form = InterestedFieldsForm(request.POST)
            if form.is_valid():
                profile = form.save(commit=False)
                profile.user = request.user
                profile.save()
        else:
            form = InterestedFieldsForm()

        return render(request, 'reg/done.html', context={'form': form})

and finally in template, inside the form I added this for loop:

{% for field in fields %}
                                <label class="containerq ant-col ant-col-md-6 ant-col-xs-8" >
                                    <span>
                                        <input type="checkbox" name="interested_fields" {% if field.slug in user.personalInfo.interested_fields %} checked="checked" {% endif %} value="{{field.title}}">
                                        <span style="margin-left:7px" class="checkmark"></span>
                                    </span>
                                    <span>{{field.title}}</span>
                                </label>
                            {% endfor %}

when I submit the form it gives me this error: cannot unpack non-iterable Field object Im new to django so I really dont know what am I doing wrong. thank you for your answers

CodePudding user response:

You should use a ModelMultipleChoiceField

interested_fields = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Field.objects.all(), required=False).
  • Related