0

I am trying to create a scheduling site and to do that I need to allow the user to select which jobs are to be schedule. Jobs are predefined by the user and thus are already saved in my Django Model. I have been able to get the job titles to show as checkbox options but how do I save which options (when multiple have been selected) have been selected so I can use only those jobs during scheduling.

I have been told to use ManyToManyField but I am unsure if I have used it correctly.

class Job(models.Model):
    Job_Name = models.CharField(max_length=100)
    Completion_Time = models.IntegerField()
    user = models.ForeignKey(User)

    def __str__(self):
        return self.Job_Name

class Selection(models.Model):
    selection = models.ManyToManyField(Job, blank=True)

class SelectForm(forms.ModelForm):
    choices = forms.ModelMultipleChoiceField(
        queryset = Job.objects.all(),
        widget = forms.CheckboxSelectMultiple)
        class Meta:
        model=Selection
        fields=("selection",)

class SelectJobView2(TemplateView):
    template_name="job_select.html"

    def post(self, request):
        form = SelectForm(request.POST)
        if form.is_valid():
            meal = form.save(commit=False)
            meal.save()
            return render(request, self.template_name, {'form' : form,})

    def get(self, request):
        form = SelectForm()
        return render(request, self.template_name, {'form' : form,})```

I want all of the selections to be saved in the Selection model so i can then use those the job object when scheduling.
  • You could you a CreateView and maybe one of those 2 posts can help you: https://stackoverflow.com/questions/53224388/django-transaction-atomic-in-createview-form-valid - https://stackoverflow.com/questions/12224442/class-based-views-for-m2m-relationship-with-intermediate-model – Higor Rossato Apr 25 '19 at 15:00
  • Could you clarify what exactly is not working? Every selection will be stored in the [through/intermediary table](https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ManyToManyField.through) of the M2M relation - not on `Selection` model itself. To access those selections from either side (`Job` or `Selection`) please read up on the [docs](https://docs.djangoproject.com/en/2.2/ref/models/relations/) – CoffeeBasedLifeform Apr 25 '19 at 18:45

0 Answers0